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

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

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

  1. a b c a b c a b c
  2. 1 12 123 4 23 567 7 12 456
  3. 2 23 456 45 56 876 4 34 234
  4. 3 34 789 47 67 345 6 76 769

output

  1. a b c
  2. 1 12 123
  3. 2 23 456
  4. 3 34 789
  5. 4 4 567
  6. 45 45 876
  7. 47 47 345
  8. 7 12 456
  9. 4 34 234
  10. 6 76 769

I'm trying to solve this in python

  1. for i in range(0,len(supplier.columns),len(col_list)):
  2. dfnew = supplier.iloc[i : i + len(col_list)]

答案1

得分: 2

你可以使用groupby.cumcount来去除重复列,并计算一个MultiIndex,然后使用stack函数:

  1. out = (df.set_axis(pd.MultiIndex
  2. .from_arrays([df.columns,
  3. df.columns.to_series()
  4. .groupby(level=0).cumcount()]),
  5. axis=1)
  6. .stack().sort_index(level=1)
  7. )

输出:

  1. a b c
  2. 0 0 1 12 123
  3. 1 0 2 23 456
  4. 2 0 3 34 789
  5. 0 1 4 23 567
  6. 1 1 45 56 876
  7. 2 1 47 67 345
  8. 0 2 7 12 456
  9. 1 2 4 34 234
  10. 2 2 6 76 769

或者使用groupbyconcat函数:

  1. group = df.columns.to_series().groupby(level=0).cumcount()
  2. out = pd.concat([g for k,g in df.groupby(group, axis=1)], axis=0)

输出:

  1. a b c
  2. 0 1 12 123
  3. 1 2 23 456
  4. 2 3 34 789
  5. 0 4 23 567
  6. 1 45 56 876
  7. 2 47 67 345
  8. 0 7 12 456
  9. 1 4 34 234
  10. 2 6 76 769
英文:

You can de-duplicate the columns with groupby.cumcount and compute a MultiIndex, then stack:

  1. out = (df.set_axis(pd.MultiIndex
  2. .from_arrays([df.columns,
  3. df.columns.to_series()
  4. .groupby(level=0).cumcount()]),
  5. axis=1)
  6. .stack().sort_index(level=1)
  7. )

Output:

  1. a b c
  2. 0 0 1 12 123
  3. 1 0 2 23 456
  4. 2 0 3 34 789
  5. 0 1 4 23 567
  6. 1 1 45 56 876
  7. 2 1 47 67 345
  8. 0 2 7 12 456
  9. 1 2 4 34 234
  10. 2 2 6 76 769

Or using groupby and concat:

  1. group = df.columns.to_series().groupby(level=0).cumcount()
  2. out = pd.concat([g for k,g in df.groupby(group, axis=1)], axis=0)

Output:

  1. a b c
  2. 0 1 12 123
  3. 1 2 23 456
  4. 2 3 34 789
  5. 0 4 23 567
  6. 1 45 56 876
  7. 2 47 67 345
  8. 0 7 12 456
  9. 1 4 34 234
  10. 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:

确定