python - 遍历 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 数据框?谢谢
解决方案
我认为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]
推荐阅读
- kubernetes - Pod 可以容忍一组污点中的一个吗
- marklogic - 光学查询中的 op:eq 函数中未发生日期比较
- wordpress - 在另一个查询中按自定义字段排序帖子
- flutter - 在滚动时加载新的数据表单服务器 | 分页 | 颤振/飞镖
- python - 将变量从一个文件导入另一个文件
- javascript - 滚动屏幕时暂停javascript计时器
- npm - 由于 sh: 1: webpack: not found 错误,无法运行 npm 命令;相同的代码库在其他地方可以正常运行命令
- java - 使用 Gradle 生成 JSON Schema 并打包到 JAR?
- python - var = input() 中断,但只是有时
- c# - 使用标签助手时如何呈现html级联