Python 划分数据帧列:TypeError:';int';对象是不可编辑的
我有一个数据帧Python 划分数据帧列:TypeError:';int';对象是不可编辑的,python,python-3.x,pandas,numpy,dataframe,Python,Python 3.x,Pandas,Numpy,Dataframe,我有一个数据帧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
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
新_列的所需输出为:
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
请注意,其工作原理如下:
其中(条件[,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
@d_kennetz,因为如果A小于或等于0,则该值必须为0。