首页 > 解决方案 > 遍历 1 列,添加到新列

问题描述

我有一个数据框 X,有 3 列 - 加速、减速和停止。有 111110 行。

我想遍历加速列中的值,以便如果该值符合某个条件,则会为 X 的加速列中的每个变量创建一个新值并将其保存在“r”中。我有以下代码-

r=[]
pos=0
while pos<=111110:
for i in X['accel']:
    if i<10:
        r.append(1)
    elif 10<=i>=20:
        r.append(2)
    elif 20<=i>=30:
        r.append(3)
    elif 30<=i>=40:
        r.append(4)
    elif i>40:
        r.append(5)
        pos+=1

frames = [r,X]
result = pd.concat(frames)

但是,当它运行时,我只会得到

for i in X['accel']:
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

如何使代码通过数据框的整个列运行,然后将 r 的值作为附加列打印到 X 数据框?谢谢

标签: pythonpandasloopsdataframe

解决方案


我认为pd.cut会起作用

pd.cut(df.accel,bins=[-np.inf,10,20,30,40,np.inf],labels =[1,2,3,4,5])
Out[339]: 
0    1
1    1
2    4
3    5
4    5
Name: accel, dtype: category
Categories (5, int64): [1 < 2 < 3 < 4 < 5]

推荐阅读