【问题标题】:Reorganize elements of Pandas Dataframe by row and column to new dataframe按行和列将 Pandas Dataframe 的元素重组为新的数据框
【发布时间】:2021-04-29 18:01:24
【问题描述】:

我确实有以下数据框:

    1    2    3      4      5      6
0  NaN  NaN  NaN     a      b     c
1  NaN  NaN  NaN     d      e     f
2  NaN  NaN  NaN     g      h     i
0  1.0  2.0 3.0   -5.0   -4.0  -36.0
1  4.0  5.0 6.0  -32.0  -31.0 -120.0
2  7.0  8.0 9.0  102.0  126.0    3.0

这是四个 Dataframe 的乘积,因此每个季度(大小 3x3)也可以作为一个独立的 pandas 数据框使用。 我需要一个结构如下的数据框:

     1  2  3  4  5  6   
1    1  a  2  d  3  g  
2    4  b  5  e  6  h  
3    7  c  8  f  9  i
       

用文字描述:

so the first  element of the third row is followed by the first element of the third Column.
      second  element of the third row  ...              second element of the third Col
      third   element of the third row  ...              third  element of the third C..

so the first  element of the fourth row is followed by the first element of the fourth Column.
      second  element of the fourth row  ...              second element of the fourth Col
      third   element of the fourth row  ...              third  element of the fourth C..

so the first  element of the fifth row is followed by the first element of the fifth Column.
      second  element of the fifth row  ...              second element of the fifth Col
      third   element of the fifth row  ...              third  element of the fifth C..

欢迎和赞赏任何想法。请考虑:

  • 6x6 是示例性数据帧,其差异可能为 4x4 或大于 6x6
  • 8x4 也可能发生

更新: 好吧,也许它可以使用 df.T(转置)数据帧右上角(abc..hi)并通过一个循环,该循环放置一列 df(下 lfet),然后是一列转置的右上数据帧。因为我现在要上班了,我明天试试看,然后再更新我的帖子

【问题讨论】:

  • 好吧,也许可以使用 df.T(转置)Dataframe 右上角(abc..hi)和

标签: python-3.x pandas dataframe itertools


【解决方案1】:

根据我的理解,您可以使用 df 的形状并抓住左下和右上矩阵并将它们连接起来:

a,b = df.shape
m = int(a/2)
x = pd.DataFrame(df.iloc[:m,np.r_[m:b]].to_numpy()).T
y = pd.DataFrame(df.iloc[m:,:m].to_numpy())

out = (pd.concat((y,x),axis=1).sort_index(axis=1)
         .set_axis(df.columns,axis=1,inplace=False))

print(out)

     1  2    3  4    5  6
0  1.0  a  2.0  d  3.0  g
1  4.0  b  5.0  e  6.0  h
2  7.0  c  8.0  f  9.0  i

【讨论】:

  • 感谢您为帮助我解决此问题所付出的努力和时间。我将尝试使用几个不同的数据框。我认为测试应该在明天完成(因为我正在为好玩而编程,我不能在工作时间测试)我希望你做得很好,周末愉快:)
  • @HansPeter 当然。我希望你一切都好 :) 周末愉快
  • 您的回答确实完美。但是我问了错误的问题,我想以错误的方式操纵我的数据。所以我稍后会针对相同的数据集和主题但不同的组合提出一个新问题。
猜你喜欢
  • 2019-08-14
  • 2020-11-05
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2018-04-22
  • 1970-01-01
相关资源
最近更新 更多