I am trying to append all column values to the first three columns couldn't able to find any approach.
Input:
cv cv new_col mg mg new_col sa sa new_col
5g 5g cv 0% zinsen zin mg a-series-owner ase sa
2xopticalcam2x zoom cv 24 hour battery hba mg all all sa
Expected OutPut:
cv cv new_col
5g 5g cv
2xopticalcam2x zoom cv
0% zinsen zin mg
24 hour battery hba mg
a-series-owner ase sa
all all sa
my approach:
oneCol = []
colLength = len(df)
for k in range(colLength):
oneCol.append(df[k])
combined = pd.concat(oneCol, ignore_index=True)
print(combined)
but I am not getting the expected output.
IIUC
step = 3
df = pd.concat([pd.DataFrame(df.iloc[:, x:x+step].values)\
for x in range(0, len(df.columns), step)],
sort=True,
ignore_index=True)
0 1 2
0 5g 5g cv
1 2xopticalcam2x zoom cv
2 0% zinsen zin mg
3 24 hour battery hba mg
4 a-series-owner ase sa
5 all all sa
You can change previous answer with creating default columns names by DataFrame.set_axis
:
df = pd.concat([v.set_axis(range(len(v.columns)), inplace=False, axis=1).assign(new_col=k)
for k, v in df.groupby(axis=1, level=0)], axis=0)
Or if always 3 values per groups:
df1 = pd.DataFrame(df.values.reshape(-1, 3))
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.