gpt4 book ai didi

python - 如何将2个pandas数据框中的2列彼此相乘

转载 作者:行者123 更新时间:2023-11-30 22:34:19 25 4
gpt4 key购买 nike

我有2个这样的数据框

    DF1:    Col1 Col2
Row1 A 30
Row2 B 40

DF2: Col1 Col2
Row1 A 10
Row2 B 5

现在我想将 DF1.Col2 和 DF2.Col2 相乘并得到这样的输出

    Out:   Col1 COl3
Row1 A 300
Row2 B 200

我该怎么做。我尝试了以下代码,但它不起作用

DF1[:,'Col3'] = pd.Series(DF1.Col2.astype(int)*DF2.Col2.astype(int),index=DF1.index)

这直接导致以下错误:类型错误:不可散列的类型

最佳答案

我认为你需要:

DF1['Col3'] = DF1.Col2.astype(int)*DF2.Col2.astype(int)
print (DF1)
Col1 Col2 Col3
Row1 A 30 300
Row2 B 40 200

另一个解决方案 mul :

DF1['Col3'] = DF1.Col2.astype(int).mul(DF2.Col2.astype(int))
print (DF1)
Col1 Col2 Col3
Row1 A 30 300
Row2 B 40 200

关于python - 如何将2个pandas数据框中的2列彼此相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com