鱼C论坛

 找回密码
 立即注册
查看: 1818|回复: 1

[已解决]两列相除的问题,求大师帮忙,谢谢

[复制链接]
发表于 2023-4-24 22:07:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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列,求大师帮忙,谢谢
最佳答案
2023-4-24 22:10:04
您好!首先,我需要您先导入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。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-4-24 22:10:04 | 显示全部楼层    本楼为最佳答案   
您好!首先,我需要您先导入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。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-15 08:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表