英文:
I'm trying to append the repeated column in a dafaframe to new dataframe
问题
a b c
1 12 123
2 23 456
3 34 789
4 4 567
45 45 876
47 47 345
7 12 456
4 34 234
6 76 769
英文:
Inuput
a b c a b c a b c
1 12 123 4 23 567 7 12 456
2 23 456 45 56 876 4 34 234
3 34 789 47 67 345 6 76 769
output
a b c
1 12 123
2 23 456
3 34 789
4 4 567
45 45 876
47 47 345
7 12 456
4 34 234
6 76 769
I'm trying to solve this in python
for i in range(0,len(supplier.columns),len(col_list)):
dfnew = supplier.iloc[i : i + len(col_list)]
答案1
得分: 2
你可以使用groupby.cumcount
来去除重复列,并计算一个MultiIndex,然后使用stack
函数:
out = (df.set_axis(pd.MultiIndex
.from_arrays([df.columns,
df.columns.to_series()
.groupby(level=0).cumcount()]),
axis=1)
.stack().sort_index(level=1)
)
输出:
a b c
0 0 1 12 123
1 0 2 23 456
2 0 3 34 789
0 1 4 23 567
1 1 45 56 876
2 1 47 67 345
0 2 7 12 456
1 2 4 34 234
2 2 6 76 769
group = df.columns.to_series().groupby(level=0).cumcount()
out = pd.concat([g for k,g in df.groupby(group, axis=1)], axis=0)
输出:
a b c
0 1 12 123
1 2 23 456
2 3 34 789
0 4 23 567
1 45 56 876
2 47 67 345
0 7 12 456
1 4 34 234
2 6 76 769
英文:
You can de-duplicate the columns with groupby.cumcount
and compute a MultiIndex, then stack
:
out = (df.set_axis(pd.MultiIndex
.from_arrays([df.columns,
df.columns.to_series()
.groupby(level=0).cumcount()]),
axis=1)
.stack().sort_index(level=1)
)
Output:
a b c
0 0 1 12 123
1 0 2 23 456
2 0 3 34 789
0 1 4 23 567
1 1 45 56 876
2 1 47 67 345
0 2 7 12 456
1 2 4 34 234
2 2 6 76 769
group = df.columns.to_series().groupby(level=0).cumcount()
out = pd.concat([g for k,g in df.groupby(group, axis=1)], axis=0)
Output:
a b c
0 1 12 123
1 2 23 456
2 3 34 789
0 4 23 567
1 45 56 876
2 47 67 345
0 7 12 456
1 4 34 234
2 6 76 769
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论