【问题标题】:Spread specific columns in dataframe without any aggregation?在数据框中传播特定列而不进行任何聚合?
【发布时间】:2021-07-26 23:58:21
【问题描述】:

这是我的玩具 df:

{'id': {0: 1089577, 1: 1089577, 2: 1089577, 3: 1089577, 4: 1089577},
 'title': {0: 'Hungarian Goulash Stew',
  1: 'Hungarian Goulash Stew',
  2: 'Hungarian Goulash Stew',
  3: 'Hungarian Goulash Stew',
  4: 'Hungarian Goulash Stew'},
 'readyInMinutes': {0: 120, 1: 120, 2: 120, 3: 120, 4: 120},
 'nutrients.amount': {0: 323.18, 1: 15.14, 2: 4.43, 3: 38.95, 4: 34.64},
 'nutrients.name': {0: 'Calories',
  1: 'Fat',
  2: 'Saturated Fat',
  3: 'Carbohydrates',
  4: 'Net Carbohydrates'},
 'nutrients.percentOfDailyNeeds': {0: 16.16,
  1: 23.3,
  2: 27.69,
  3: 12.98,
  4: 12.6},
 'nutrients.title': {0: 'Calories',
  1: 'Fat',
  2: 'Saturated Fat',
  3: 'Carbohydrates',
  4: 'Net Carbohydrates'},
 'nutrients.unit': {0: 'kcal', 1: 'g', 2: 'g', 3: 'g', 4: 'g'}}

我想将nutrients.title 传播为列。 Sp 我将得到 Fat, Saturated Fat ... 列及其相应的值,没有任何 agg。

什么函数可以在没有任何聚合的情况下做到这一点?只是“重塑”。

我希望它是:

我怎样才能这样“传播”它?

【问题讨论】:

  • their corresponding values 是什么意思?您对输入数据的预期输出是什么?
  • @QuangHoang 我有具有营养素名称的营养素.title 列,我需要将它们设为列,以传播它们。
  • 我了解您希望将它们 (title) 作为列。指数呢?单元格的值是多少?
  • 如果您有一个示例说明您希望输出 df 的样子,将会有所帮助。
  • @dm2 我已经用期望的结果编辑了 Q,我正在尝试使用枢轴和融化函数

标签: python python-3.x pandas reshape melt


【解决方案1】:

试试pivot_table

# Rename Columns
df.columns = df.columns.map(lambda x: f".{x.split('.')[-1]}" if '.' in x else x)

# Create Pivot Table
df = df.pivot_table(
    index=['id', 'title', 'readyInMinutes'],
    columns=['.title'],
    values=['.amount',
            '.percentOfDailyNeeds',
            '.unit'],
    aggfunc='first'
).reset_index() \
    .swaplevel(0, 1, axis=1)

# Re-Order Columns So that nutrients.title are grouped
df = df.reindex(sorted(df.columns), axis=1)

# Reduce Levels by join
df.columns = df.columns.map(''.join)

print(df.to_string(index=False))

输出:

id readyInMinutes title Calories.amount Calories.percentOfDailyNeeds Calories.unit Carbohydrates.amount Carbohydrates.percentOfDailyNeeds Carbohydrates.unit Fat.amount Fat.percentOfDailyNeeds Fat.unit Net Carbohydrates.amount Net Carbohydrates.percentOfDailyNeeds Net Carbohydrates.unit 饱和脂肪.amount 饱和脂肪.percentOfDailyNeeds饱和脂肪单位 1089577 120 炖匈牙利炖牛肉 323.18 16.16 大卡 38.95 12.98 g 15.14 23.3 g 34.64 12.6 g 4.43 27.69 g

带有删节输出的步骤

  1. 更改列名:
print(df.columns.values)
# ['id' 'title' 'readyInMinutes' 'nutrients.amount' 'nutrients.name'
#  'nutrients.percentOfDailyNeeds' 'nutrients.title' 'nutrients.unit']
print(df.columns.map(lambda x: f".{x.split('.')[-1]}" if '.' in x else x).values)
# ['id' 'title' 'readyInMinutes' '.amount' '.name' '.percentOfDailyNeeds'
#  '.title' '.unit']
  1. 使用单个标题列透视多个值列以创建多级列索引:
print(df.pivot_table(
    index=['id', 'title', 'readyInMinutes'],
    columns=['.title'],
    values=['.amount',
            '.percentOfDailyNeeds',
            '.unit'],
    aggfunc='first'
).to_string())
。数量 .title 卡路里 碳水化合物 脂肪 净碳水化合物 饱和脂肪 id 标题 readyInMinutes 1089577 匈牙利炖牛肉 120 323.18 38.95 15.14 34.64 4.43
  1. 修复索引和交换级别,以便标签位于顶部(CaloriesCarbohydrates 等) .reset_index().swaplevel(0, 1, axis=1)
.title 卡路里 碳水化合物 脂肪 净碳水化合物 饱和脂肪 id 标题 readyInMinutes .amount .amount .amount .amount .amount 0 1089577 匈牙利炖牛肉 120 323.18 38.95 15.14 34.64 4.43
  1. 对列进行排序,以便标签放在一起:
df = df.reindex(sorted(df.columns), axis=1)
.title 卡路里 碳水化合物 id readyInMinutes 标题 .amount .percentOfDailyNeeds .unit .amount .percentOfDailyNeeds .unit 0 1089577 120 匈牙利炖炖牛肉 323.18 16.16 kcal 38.95 12.98 g
  1. 使用连接降低级别(创建Calories.amountCalories.unit 等)
df.columns = df.columns.map(''.join)
id readyInMinutes 标题 Calories.amount Calories.percentOfDailyNeeds Calories.unit 0 1089577 120 匈牙利炖牛肉 323.18 16.16 kcal

【讨论】:

  • 但是我还需要单位和日常需求列,我应该在id上合并吗?
  • 完成了,请看一下我的excel图片,我希望它是怎样的,我希望现在它更清楚了。
  • 我的解决方案是制作几张桌子并加入id
  • 我希望所有的营养素名称都在列中,以及它们的单位和每日百分比。对于每种营养素,您应该在最终数据框中获得 3 列。
  • 亨利?你明白了吗?也许我们可以快速缩放?
【解决方案2】:

你可以使用df.pivot()如下:

(df.pivot(index=['id', 'title', 'readyInMinutes'], 
          columns='nutrients.title', 
          values='nutrients.amount')
          .rename_axis(None, axis=1)
).reset_index()

结果:

        id                   title  readyInMinutes  Calories  Carbohydrates    Fat  Net Carbohydrates  Saturated Fat
0  1089577  Hungarian Goulash Stew             120    323.18          38.95  15.14              34.64           4.43

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2019-08-31
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多