【问题标题】:Transforming the data from a single column into multiple columns in pandas将数据从单列转换为熊猫中的多列
【发布时间】:2021-09-22 22:32:25
【问题描述】:

我正在使用包含以下结构的数据库

ID Test Result
12a Test1 Normal
12a Test3 678.2
3s5 Test2 <1
3s5 Test1 Normal
8r5 Test4 Rectangular(3+)

如您所见,不同的测试有不同的结果格式,并不是每个 ID 都有所有的测试。

我想把它变成如下:

ID Test1 Test2 Test3 Test4
12a Normal NA 678.2 NA
3s5 Normal <1 NA NA
8r5 NA NA NA Rectangular(3+)

我尝试过pandas.pivot,但遇到以下错误

df.pivot(index="ID",columns="Test",values="Result")

ValueError: Index contains duplicate entries, cannot reshape

将索引更改为 ID 无效,重置索引也无效。

任何帮助将不胜感激!

【问题讨论】:

标签: python pandas pivot pivot-table


【解决方案1】:

你可以尝试用.pivot_table()代替.pivot(),如下:

df.pivot_table(index="ID", columns="Test", values="Result", aggfunc='first')

结果:

Test   Test1 Test2  Test3            Test4
ID                                        
12a   Normal   NaN  678.2              NaN
3s5   Normal    <1    NaN              NaN
8r5      NaN   NaN    NaN  Rectangular(3+)

【讨论】:

  • 谢谢!我曾尝试使用pivot_table,但缺少aggfunc="first" 参数。像魅力一样工作!
  • @Mario_B 如果没有aggfunc="first" 参数,默认值为aggfunc='mean',它需要数值才能正常工作。由于您的数据包含非数字数据,因此使用aggfunc="first" 是让pivot_table() 处理此类数据的技巧。
【解决方案2】:

这是一种方法:

df = {'ID': ['12a', '12a', '3s5', '3s5', '8r5'],
  'Test': ['Test1', 'Test3', 'Test2', 'Test1', 'Test4'],
  'Result': ['Normal', '678.2', '<1', 'Normal', 'Rectangular(3+)']}

df=df.groupby(['ID', 'Test'])['Result'].sum().unstack(fill_value="NA")

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 2019-07-14
    • 2019-10-12
    • 1970-01-01
    • 2021-05-27
    • 2021-08-08
    • 1970-01-01
    • 2016-09-25
    • 2021-01-11
    相关资源
    最近更新 更多