简体   繁体   English

遍历 Pandas DataFrame 的连续 N 列

[英]Iterate over Consecutive N Columns of Pandas DataFrame

I have a Pandas DataFrame.我有一个 Pandas DataFrame。

dff = pd.DataFrame([[1,2,3,4,5,6,7]],columns = ['A','B','C','D','E','F','G'])
print(dff)

A   B   C   D   E   F   G
1   2   3   4   5   6   7
10  20  30  40  50  60  70

I am Trying to iterate row 1 such that, at a time I could get three Column values at a time ie for columns A,B,C then B,C,D, followed by D,E,F and E,F,G我正在尝试迭代第 1 行,这样我一次可以获得三个列值,即 A、B、C 列,然后是 B、C、D,然后是 D、E、F 和 E、F、G

Sample Pseudocode:示例伪代码:

for row in df.iterrows():
    # For 1 row run iteration for consecutive 3 columns and print results.
    Print(#some function output)
    Print("*******")

Expected Output:预期 Output:

1,2,3
2,3,4
3,4,5
4,5,6
5,6,7
*******
10,20,30
20,30,40
30,40,50
40,50,60
50,60,70

I was trying to iterate through columns but couldn't find the right approach.我试图遍历列,但找不到正确的方法。

You can do你可以做

a = np.concatenate( [np.array([np.array(x[i:i+3]) for i in range(len(x)-2)]) for x in df.values])
df = pd.DataFrame(a)
df
Out[226]: 
    0   1   2
0   1   2   3
1   2   3   4
2   3   4   5
3   4   5   6
4   5   6   7
5  10  20  30
6  20  30  40
7  30  40  50
8  40  50  60
9  50  60  70

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM