【问题标题】:how to split the data? [closed]如何拆分数据? [关闭]
【发布时间】:2020-08-01 16:54:45
【问题描述】:

我想从数据中拆分电影制作公司名称..需要提取公司名称。

df['production_companies'].head(20)

0     [{'name': 'Pixar Animation Studios', 'id': 3}]
1     [{'name': 'TriStar Pictures', 'id': 559}, {'na...
3     [{'name': 'Twentieth Century Fox Film Corporat...
4     [{'name': 'Sandollar Productions', 'id': 5842}...
5     [{'name': 'Regency Enterprises', 'id': 508}, {...
8     [{'name': 'Universal Pictures', 'id': 33}, {'n...
9     [{'name': 'United Artists', 'id': 60}, {'name'...
10    [{'name': 'Columbia Pictures', 'id': 5}, {'nam...
12    [{'name': 'Universal Pictures', 'id': 33}, {'n...
13    [{'name': 'Hollywood Pictures', 'id': 915}, {'...
14    [{'name': 'Le Studio Canal+', 'id': 183}, {'na...
15    [{'name': 'Universal Pictures', 'id': 33}, {'n...
16    [{'name': 'Columbia Pictures Corporation', 'id...
17    [{'name': 'Miramax Films', 'id': 14}, {'name':...
18    [{'name': 'O Entertainment', 'id': 5682}, {'na...
19             [{'name': 'Columbia Pictures', 'id': 5}]
20    [{'name': 'Jersey Films', 'id': 216}, {'name':...
22    [{'name': 'Silver Pictures', 'id': 1885}, {'na...
24    [{'name': 'United Artists', 'id': 60}, {'name'...
26              [{'name': 'New Line Cinema', 'id': 12}]
Name: production_companies, dtype: object

【问题讨论】:

  • df['production_companies'] = df['production_companies'].apply(ast.literal_eval) df['production_companies'] = df['production_companies'].fillna("[]"). apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])

标签: python python-3.x pandas jupyter-notebook


【解决方案1】:

我们可以explode()然后从字典中获取个人name并重置索引inplace

df['name']=df['production_companies'].explode().apply(lambda x:x['name']).reset_index(drop=True)

【讨论】:

  • TypeError: 字符串索引必须是整数
  • 修改后可以试一下吗。我使用了这个示例数据框 df=pd.DataFrame({'production_companies':[[{'name':'ABC','id':1}],[{'name':'CDE','id' :2},{'name':'DEF','id':3}],[{'name':'FDE','id':4}]]}) 并且工作正常
  • 好的,让我看看你的示例数据框。
  • 但是在我的情况下我仍然遇到错误。
【解决方案2】:

我们可以explode

s = df['production_companies'].explode()
namedata = pd.DataFrame(s.tolist(),index=s.index)

【讨论】:

  • 我也需要拆分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
相关资源
最近更新 更多