I have a 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
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.