【问题标题】:pandas dataset transformation to normalize the datapandas 数据集转换以规范化数据
【发布时间】:2020-03-20 16:20:25
【问题描述】:

我有一个这样的 csv 文件:

我想将它转换成这样的熊猫数据框:

基本上我正在尝试规范化数据集以填充 sql 表。

我已经使用 json_normalize 从流派列中创建了一个单独的数据集,但我不知道如何转换这两个列,如上图所示。

我们将非常感谢您提出一些建议。

【问题讨论】:

  • 避免将示例数据添加为图片,无法将其复制并粘贴到编辑器中以供我们自己使用。将您的示例数据添加为文本。

标签: python json pandas denormalized


【解决方案1】:

如果genre_id是唯一的数值(如图),你可以使用如下:

#find all occurrences of digits in the column and convert the list items to comma separated string.
df['genre_id'] = df['genres'].str.findall(r'(\d+)').apply(', '.join)

#use pandas.DataFrame.explode to generate new genre_ids by comma separating them.
df = df.assign(genre_id = df.genre_id.str.split(',')).explode('genre_id') 

#finally remove the extra space
df['genre_id']  = df['genre_id'].str.lstrip() 

#if required create a new dataframe with these 2 columns only
df = df[['id','genre_id']]

【讨论】:

  • 谢谢。它在我更新我的熊猫版本后工作,因为数据框的 explode() 属性仅在熊猫 0.25 及更高版本中可用。
猜你喜欢
  • 2012-09-13
  • 2010-10-06
  • 2023-03-26
  • 1970-01-01
  • 2014-09-06
  • 2021-10-17
  • 1970-01-01
  • 2015-12-08
  • 2015-08-21
相关资源
最近更新 更多