|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
data =[["2345","A","2022-12-20","2.1016","-0.72","-0.77"],["004243","C","2022-12-15","2.0891","","-0.77"],
["519212","B","2022-12-10","","1.9733","-0.77","-3.29"],["162411","E","2022-12-9","0.7071","-1.64","-1.46"],
["007844","FC","2022-11-19","0.6967",None,"-1.46"],["163208","G","2022-11-10","1.0440","-0.40","-0.40"]]
columns = ["编号","名称","日期","AA","BB","C","数值88"]
df2=pd.DataFrame(data,columns =columns)
print(df2)
想新增新列AB
df2['AB'] = df2['AA'] /df2['BB']
使有数字的都能得出一个新数字,要如何处理2列,求大师帮忙,谢谢
您好!首先,我需要您先导入Pandas库。接着,我们可以使用pd.to_numeric()函数将这两列转换为数字,然后相除以创建新列"AB"。以下是您需要的代码:
import pandas as pd
data =[["2345","A","2022-12-20","2.1016","-0.72","-0.77"],["004243","C","2022-12-15","2.0891","","-0.77"],
["519212","B","2022-12-10","","1.9733","-0.77","-3.29"],["162411","E","2022-12-9","0.7071","-1.64","-1.46"],
["007844","FC","2022-11-19","0.6967",None,"-1.46"],["163208","G","2022-11-10","1.0440","-0.40","-0.40"]]
columns = ["编号","名称","日期","AA","BB","C","数值88"]
df2 = pd.DataFrame(data, columns=columns)
print(df2)
# 将'AA'和'BB'两列转换为数字类型,并将无法转换的值替换为NaN
df2['AA'] = pd.to_numeric(df2['AA'], errors='coerce')
df2['BB'] = pd.to_numeric(df2['BB'], errors='coerce')
# 计算新列'AB'
df2['AB'] = df2['AA'] / df2['BB']
print(df2)
运行上述代码后,您将得到包含新列"AB"的DataFrame。"AB"列的值为"AA"列除以"BB"列的值,非数字的值将转换为NaN。
|
|