簡體   English   中英

遍歷 Pandas DataFrame 的連續 N 列

[英]Iterate over Consecutive N Columns of 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

我正在嘗試迭代第 1 行,這樣我一次可以獲得三個列值,即 A、B、C 列,然后是 B、C、D,然后是 D、E、F 和 E、F、G

示例偽代碼:

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

預期 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

我試圖遍歷列,但找不到正確的方法。

你可以做

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