Pandas新增数据列
四种方法,可以新增数据列
直接赋值
df.apply方法
df.assign方法
按条件选择分组分别赋值
1、直接赋值
注意,df["bWendu"]其实是一个Series,后面减去的返回的是Series
df.loc[:,"wencha"] = df["bWendu"] - df["yWendu"] print(df.head())
多一列为wencha
2、df.apply方法
需求:
实例:添加一列温度类型:
如果最高温度大于33度就是高温
低于-10度是低温
否则是常温
注意需要设置axis = 1 ,这是series
def get_wendu_type(x): if x["bWendu"] > 33: return "高温" if x["yWendu"] < -10 : return "低温" return "常温"df.loc[:,"wendu_type"] = df.apply(get_wendu_type,axis = 1)print(df)
image.png
查看温度类型的计数
wendu_count = df["wendu_type"].value_counts() print(wendu_count)
温度类型计数运行结果
3、df.assign方法
可以同时添加多个新的列,不会改变df本身,会生成一个新的Dataframe
c =df.assign( yWendu_huashi = lambda x : x["yWendu"] * 9 / 5 + 32, # 摄氏度转华氏度 bWendu_huashi = lambda x : x["bWendu"] * 9 / 5 + 32)print(c.head())
运行结果
4、按条件选择分组分别赋值
按条件先选择数据,然后对这部分数据赋值新列
实例:高低温差大于10度,则认为温差大
# 先创建空列(这是第一种创建新列的方法) df['wencha_type'] = '' df.loc[df["bWendu"]-df["yWendu"]>10, "wencha_type"] = "温差大" df.loc[df["bWendu"]-df["yWendu"]<=10, "wencha_type"] = "温差正常" wencha_count = df["wencha_type"].value_counts() print(wencha_count)
作者:测试探索
链接:https://www.jianshu.com/p/1a0be6b5c3d7