按索引和步骤 2 循环访问数据帧列

Iterate over dataframe columns by index and step 2

提问人:mahmood 提问时间:11/17/2023 更新时间:11/17/2023 访问量:48

问:

对于这样的数据帧

      M1_x      M1_y         M2_x         M2_y
0        2  0.861626            2     0.980591
1        4  0.685437            4     0.647706
2        8  0.495346            8     0.303102
3       16  0.327949           16     0.133477

我想画两条线,M1 和 M2,每条线都有 X 和 Y 点。通过像这样迭代列:

n = df_scales.shape[1]-1   // Number of columns is 4, we iterate 0,1 and 2,3
for index in n:
    x = df_scales.iloc[:, index]
    y = df_scales.iloc[:, index+1]
    plt.plot( x, y, marker = 'o')
    plt.show()

但是我收到这个错误:

    for index in n:

TypeError: 'int' object is not iterable

我该如何解决这个问题?还是更好的方法?

Python 数据帧

评论


答:

2赞 user19077881 11/17/2023 #1

您可以使用:

for idx in range(0,len(df_scales.columns),2):
    x = df_scales.iloc[:, idx]
    y = df_scales.iloc[:, idx+1]
    plt.plot(x, y, marker = 'o')
plt.show()

enter image description here

1赞 Marco Parola 11/17/2023 #2

尝试以下操作,在检索列数后,使用 step=2 对其进行迭代

n = len(df_scales.columns)
for index in range(0, n, 2):
    # your code

评论

1赞 user19077881 11/17/2023
df_scales.columnsIndex 的类型不是 int,因此在传递给 range() 时会导致错误。
0赞 Marco Parola 11/17/2023
谢谢,这是一个错误堆栈..我通过添加一个len()