遍历1列,添加到新列

时间:2018-07-17 14:14:52

标签: python pandas loops dataframe

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

我想遍历accel列中的值,以便如果该值符合特定条件,则会为X accel列中的每个变量创建一个新值并将其保存在'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数据框的附加列? 谢谢

1 个答案:

答案 0 :(得分:3)

我认为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]
相关问题