【问题标题】:Transpose every nth rows from one column to multiple columns using pandas使用 pandas 将每 n 行从一列转置为多列
【发布时间】:2021-01-10 12:18:51
【问题描述】:

有人可以建议我如何使用 pandas 将每 n 行从一列转换为多列。假设我有一个包含以下内容的数据框:-

index 0
0 275
1 0.81
2 388
3 2.26
4 275
5 0.93
6 447
7 2.60
8 275
9 1.05
10 500
11 2.91
12 275
13 1.15
14 549
15 3.20

想要的输出:-

index "A" "B" "C" "D"
0 275 0.81 388 2.26
1 275 0.93 447 2.60
2 275 1.05 500 2.91
3 275 1.15 549 3.20

我试过pd.wide_to_long,但没用。

df3 = pd.wide_to_long(df, stubnames= '0', i='index', j='id')

非常感谢任何建议。谢谢。

【问题讨论】:

  • 看看numpy.reshape
  • 帮助 OP @Ch3steR
  • @sammywemmy 我在移动 rn 上。写不出答案。 np.reshape 有时会失败,但如果 shape7 并且 OP 想要 2 列,则会引发错误。为了使它起作用,使用fill_value 填充会起作用,但OP 没有指定任何关于它的内容。看起来有人已经回答了;)

标签: python python-3.x pandas


【解决方案1】:

您可以使用np.reshape() 函数来实现。 请按照给定的步骤:

第 1 步:将数据框列数据转换为 numpy 数组

import numpy as np
arr = np.array(df[0]

第 2 步:然后将此数组数据重塑为所需的列数

array2 = np.reshape(arr, (4, 4)) # here (4, 4) are the number of rows and columns

第 3 步:为您的重构数组创建一个新的数据框

df3 = pd.DataFrame(array2, columns = {'A', 'B', 'C', 'D'})

现在您的旧数据框已更改为您想要的列数的数据框。

【讨论】:

    【解决方案2】:

    已经回答了另一个问题:

    
    print (pd.DataFrame(df.values.reshape(-1, 4), 
                        columns=['A','B','C','D']))
    

    在这里查看:

    Transpose the data in a column every nth rows in PANDAS

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多