我正在尝试将数据框中重复的列附加到新数据框中。

huangapple go评论169阅读模式
英文:

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

或者使用groupbyconcat函数:

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

Or using groupby and concat:

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

huangapple
  • 本文由 发表于 2023年7月3日 16:57:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定