【问题标题】:TypeError: string indices must be integers (in lambda function)TypeError:字符串索引必须是整数(在 lambda 函数中)
【发布时间】:2021-09-07 09:18:39
【问题描述】:

我的数据集是这样的

url         boolean          details                                             
                                                                                       numberOfPages       date
xzy.com     0                {'https://www.eltako.depdf': {'numberOfPages': 440, 'date': '2017-09-20'},'https://new.com': {'numberOfPages': 240, 'date': '2017-09-20'} }

numberOfPages 和 date col 最初是空的,而 details col 有一个字典。我想遍历所有行(url)并检查他们的details 列。对于详细信息列中的每个键,我想创建一个单独的行,然后使用 numberOfPages 和日期值来添加列值。结果应该是这样的:

url         boolean          pdfLink                             numberOfPages   date           
xzy.com     0                https://www.eltako.depdf            440             2017-09-20
                             https://new.com                     240             2017-09-20

我试过了,但第二行给了我一个错误:TypeError: string indices must be integers

def arrange(df):
    
    df=df.explode('details').reset_index(drop=True)
    out=pd.DataFrame(df['details'].map(lambda x:[x[y] for y in x]).explode().tolist())

【问题讨论】:

  • 因为details列里面的字典其实是字符串而不是字典

标签: python pandas dataframe dictionary data-science


【解决方案1】:

如果我正确理解您的代码,那么 lambda 函数期望每个 x 是一个字符串,对吗?

使用x[y] 期望y 是一个整数并要求xyth 元素。

您可以直接访问字符串的每个字符:

y for y in x

【讨论】:

  • 感谢您的编辑。无法弄清楚如何在手机上进行代码格式化。
  • 那么爆炸不会正确发生。它添加了一个列“0”,其中在不同的行中有 h t t p s 个字符。基本上是信息行
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 2021-04-28
  • 2020-06-24
  • 2016-03-26
  • 2017-09-07
  • 2018-08-19
  • 2016-02-17
相关资源
最近更新 更多