Below is a sample of a pandas dataframe, a single column with 1000’s of rows.
I need second/third columns putting data in rows 1 and 2, 4 and 5 etc in the second/third column
JavaScript
x
11
11
1
0
2
0 \path_1file1.csv
3
1 23082022 DS
4
2 520i2146002
5
3 \path_2file2.csv
6
4 230822 NS
7
5 520i2146002
8
4 \path_3file3.csv
9
5 24082022 DS
10
6 520i2146002
11
Desired Output
JavaScript
1
6
1
0 1 2
2
0 \path_1file1.csv 23082022 DS 520i2146002
3
1 \path_2file2.csv 230822 NS 520i2146002
4
2 \path_3file3.csv 24082022 DS 520i2146002
5
6
Can only manage to pull out the odds with:
JavaScript
1
2
1
df = pd.DataFrame({0: df[0].iloc[::2].values, 'value': df[0].iloc[1::2].values})
2
Suggestions?
Advertisement
Answer
Make three subsets by taking every third value – starting at 0, 1, and 2. Reset each subset’s index, and concat them all together.
JavaScript
1
5
1
df = pd.concat([df.loc[::3].reset_index(drop=True),
2
df.loc[1::3].reset_index(drop=True),
3
df.loc[2::3].reset_index(drop=True)], axis=1, ignore_index=True)
4
print(df)
5
Output:
JavaScript
1
5
1
0 1 2
2
0 \path_1file1.csv 23082022 DS 520i2146002
3
1 \path_2file2.csv 230822 NS 520i2146002
4
2 \path_3file3.csv 24082022 DS 520i2146002
5
Slightly more concise:
JavaScript
1
3
1
df = pd.concat([df.loc[i::3].reset_index(drop=True) for i in range(3)],
2
axis=1, ignore_index=True)
3