[英]Python Pandas: Append all other column values to first 3 columns
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
: 您可以通过
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: 或者如果每组总是3个值:
df1 = pd.DataFrame(df.values.reshape(-1, 3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.