Pandas给表格使用apply同时添加多列
Pandas给表格使用apply同时添加多列。
·
import os
import pandas as pd
os.chdir(r'F:\ant_python\代码03_Python使用Pandas入门数据分析\ant-learn-pandas')
df = pd.read_csv("./datas/beijing_tianqi/beijing_tianqi_2017-2019.csv")
'''
# df['yWendu'] = df['yWendu'].str.replace('℃','').astype(int) # 反复运行会报错
# AttributeError: Can only use .str accessor with string values!
# df.apply(my_func,axis=1) # 不加result_type='expand',仅返回元组
'''
df['bWendu'] = df['bWendu'].apply(lambda x :int(str(x).replace('℃','')))
df['yWendu'] = df['yWendu'].apply(lambda x :int(str(x).replace('℃','')))
df.head()
def my_func(row):
return row['bWendu']- row['yWendu'],(row['bWendu']+ row['yWendu'])/2
df[['wencha','avg']] = df.apply(my_func,axis=1,result_type='expand')
df.head()
更多推荐
已为社区贡献2条内容
所有评论(0)