【问题标题】:unable to parse specific value from a particular column of a csv file无法从 csv 文件的特定列解析特定值
【发布时间】:2019-05-28 12:56:16
【问题描述】:

我正在制作一个预测模型来预测收入并尝试从数据框中解析这个 'cast' 值,因为它不是 list字典

x['cast']

输出是

0    [{'cast_id': 4, 'character': 'Lou', 'credit_id...
1    [{'cast_id': 1, 'character': 'Mia Thermopolis'...
2    [{'cast_id': 5, 'character': 'Andrew Neimann',...
3    [{'cast_id': 1, 'character': 'Vidya Bagchi', '...
4    [{'cast_id': 3, 'character': 'Chun-soo', 'cred...
5    [{'cast_id': 6, 'character': 'Pinocchio (voice...
6    [{'cast_id': 23, 'character': 'Clyde', 'credit...
7    [{'cast_id': 2, 'character': 'Himself', 'credi...
8    [{'cast_id': 1, 'character': 'Long John Silver...
9    [{'cast_id': 24, 'character': 'Jonathan Steinb...
Name: cast, dtype: object

我需要一个列表中的所有 'character' 值。 但是当我尝试

x['cast'][0]['character']

它会抛出这个错误

TypeError: string indices must be integers

请帮帮我。

【问题讨论】:

  • 我刚刚搜了一下,它是一个json文件,但我仍然无法将它加载为'json.load(x['cast'])'
  • type(x.at[0, 'cast']) 显示什么?长话短说:是字符串还是列表?
  • @SergeBallesta - 检查第一句话 - I am making a predictive model to predict revenue and trying to parse this 'cast' value from the data frame as it is not a list or a dict
  • @jezrael:您可能是对的,但在这种情况下,我认为应该在 输入数据帧之前修复它。
  • 恕我直言,您应该想知道此列值的来源,以及如何避免该问题。

标签: json python-3.x pandas csv


【解决方案1】:

首先将json转换为字典列表,然后通过dict的键从第一个列表中获取值:

import ast

mask = x['cast'].notna()

x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(ast.literal_eval)
#alternative
#x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(pd.io.json.loads)
x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(lambda x: x[0].get('character', 'not match data'))

编辑:

如果仍有问题,请使用Series.str.extract:

x = pd.DataFrame({'cast':[[{'cast_id': 4, 'character': 'Lou'}], np.nan]})

x['cat'] = x['cast'].astype(str).str.extract("'character': '([^'']+)'")
print (x)
                                   cast  cat
0  [{'cast_id': 4, 'character': 'Lou'}]  Lou
1                                   NaN  NaN

【讨论】:

  • @AAKARSHYADAV - 你现在可以测试了吗?
  • @AAKARSHYADAV - 您现在可以查看吗?
猜你喜欢
  • 2019-05-03
  • 2019-09-27
  • 2017-05-14
  • 1970-01-01
  • 2014-10-09
  • 2016-12-24
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
相关资源
最近更新 更多