【问题标题】:converting a list of dictionary from a single column of a Data Frame into different columns in pandas将字典列表从数据框的单列转换为熊猫中的不同列
【发布时间】:2021-01-11 23:54:45
【问题描述】:

我有一个名为“data”的数据框

  updated_at          values                            user_id
0 2020-08-18    [{'value': 3742, 'key': '0'},       178414113
                 {'value': 3813, 'key': '1'}, 
                 {'value': 3918, 'key': '2'}, 
                 {'value': 2956, 'key': '3'}]   
1 2020-08-19    [{'value': 3542, 'key': '0'},       152285823
                 {'value': 2563, 'key': '1'}, 
                 {'value': 3218, 'key': '2'}, 
                 {'value': 2152, 'key': '3'}]       

我想这样转换。

updated_at 值键 user_id

0 2020-08-18      3742           0               178414113
1 2020-08-18      3813           1               178414113 
2 2020-08-18      3918           2               178414113
3 2020-08-18      2956           3               178414113
4 2020-08-19      3542           0               152285823
5 2020-08-19      2563           1               152285823
6 2020-08-19      3218           2               152285823
7 2020-08-19      2152           3               152285823

请帮助我。 我试过了

data_new = pd. Data Frame ( data ['values'].values. to list(), index= data. index)

但是没有用。

【问题讨论】:

  • 你研究过explode() 方法吗?
  • 爆炸不起作用

标签: pandas list dataframe dictionary data-wrangling


【解决方案1】:

您可以使用explode() 方法将列表列扩展为这些列表中每个条目的单独行。然后,您可以利用apply(pd.Series) 在每一行中展开结果字典:

exploded = df.explode('values').reset_index(drop=True)
exploded[['value','key']] = exploded['values'].apply(pd.Series)
exploded.drop('values', axis=1, inplace=True)

产量:

   updated_at    user_id  value key
0  2020-08-18  178414113   3742   0
1  2020-08-18  178414113   3813   1
2  2020-08-18  178414113   3918   2
3  2020-08-18  178414113   2956   3
4  2020-08-19  152285823   3542   0
5  2020-08-19  152285823   2563   1
6  2020-08-19  152285823   3218   2
7  2020-08-19  152285823   2152   3

【讨论】:

  • 第二行出现错误。错误:=列必须与键长度相同
  • 列表中包含的字典是否具有可变数量的键值对?我的解决方案适用于您原始问题中的示例数据。
  • 问题出在爆炸功能上。它不会在列表中拆分多个(值和键)字典
猜你喜欢
  • 2016-09-06
  • 2017-12-12
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 2020-01-04
  • 2021-09-07
相关资源
最近更新 更多