gpt4 book ai didi

python - 划分数据框列: TypeError: 'int' object is not iterable

转载 作者:行者123 更新时间:2023-12-01 00:56:43 25 4
gpt4 key购买 nike

我有一个数据框df,如下所示:

           A       B
0 0 4140
1 0.142857 1071
2 0 1196
3 0.090909 2110
4 0.083333 1926
5 0.166667 1388
6 0 3081
7 0 1149
8 0 1600
9 0.058824 1873
10 0 3960
: : :
19 0 4315
20 0 2007
21 0.086957 3323
22 0.166667 1084
23 0.5 2703
24 0 1214
25 0 1955
26 0 6750
27 0 3240
28 0 1437
29 0 1701

我正在尝试使用以下代码行尝试生成一个新列,如果 A 大于 0(否则填充 0),则该列将 A/B 相除,然后乘以 90:

df['new_column'] = np.where(df['A'] = 0, 0.0, df['A'].divide(df['B']))*90.0

但是我收到了该行的错误:

 result[:] = [tuple(x) for x in values]

TypeError: 'int' object is not iterable

new_column 所需的输出是:

           A     B   new_column
0 0 4140 0
1 0.142857 1071 0.01200479
2 0 1196 0
3 0.090909 2110 0.003877635
4 0.083333 1926 0.003894065
5 0.166667 1388 0.010806938
6 0 3081 0
7 0 1149 0
8 0 1600 0
9 0.058824 1873 0.002826567
10 0 3960 0
: : : :
19 0 4315 0
20 0 2007 0
21 0.086957 3323 0.00235514
22 0.166667 1084 0.013837666
23 0.5 2703 0.016648169
24 0 1214 0
25 0 1955 0
26 0 6750 0
27 0 3240 0
28 0 1437 0
29 0 1701 0

最佳答案

请注意numpy.where工作原理为:

numpy.where(condition[, x, y])

因此:

import pandas as pd

df = pd.DataFrame({'A':[0,0.142857,0,0.090909],
'B':[4140,1071,1196,2110]})

df['new_column'] = np.where(df['A'] > 0, df['A']*90/df['B'], 0)

输出

           A       B    new_column
0 0.000000 4140 0.000000
1 0.142857 1071 0.012005
2 0.000000 1196 0.000000
3 0.090909 2110 0.003878

关于python - 划分数据框列: TypeError: 'int' object is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193602/

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