【问题标题】:iterating through a nested list of strings to get first item遍历嵌套的字符串列表以获取第一项
【发布时间】:2021-06-30 16:33:16
【问题描述】:

我正在尝试从数据框中的 gen 列中提取项目(示例如下)。我的目标是将gen 中的每一行迭代到一个新的数据框列中,其中包含与预定义列表genre_code 匹配的项目。

df = pd.DataFrame({'id': [620, 843, 986], 'tit': ['AAA', 'BBB', 'CCC'], 'gen': [['Romance', 'Satire', 'Fiction'], ['Science Fiction', 'Novel'], ['Mystery', 'Novel']]})

genre_code = ['Science Fiction', 'Mystery', 'Non-fiction']

到目前为止,我能够提出以下建议:

new_gen = []
for i in df['gen']:
  for j in i:
    if j in genre_code:
      new_gen.append(j)
    else:
      new_gen.append('NA')
df['gen'] = new_gen

确实会遍历列,但生成的 new_gen 的长度与原始数据帧的行长度不匹配。

/usr/local/lib/python3.7/dist-packages/pandas/core/internals/construction.py in sanitize_index(data, index)
    746     if len(data) != len(index):
    747         raise ValueError(
--> 748             "Length of values "
    749             f"({len(data)}) "
    750             "does not match length of index "

ValueError: Length of values (30004) does not match length of index (12841)

我知道这一定是非常基本的东西,但有人可以指出我缺少什么吗?

【问题讨论】:

    标签: python pandas loops nested-lists


    【解决方案1】:

    如果您想根据您的列表过滤gen 列,您可以这样做:

    df["gen"] = df["gen"].apply(lambda x: [g for g in x if g in genre_code])
    print(df)
    

    打印:

        id  tit                gen
    0  620  AAA                 []
    1  843  BBB  [Science Fiction]
    2  986  CCC          [Mystery]
    

    P.S:为了加快处理速度,您可以将genre_code转换为set()之前:

    genre_code = set(["Science Fiction", "Mystery", "Non-fiction"])
    df["gen"] = df["gen"].apply(lambda x: [g for g in x if g in genre_code])
    

    【讨论】:

      【解决方案2】:

      我会将列表转换为字符串,然后使用series.str.findall 返回匹配的genre_code:

      df['new_gen'] = df['gen'].astype(str).str.findall('|'.join(genre_code))
      

      print(df)
      
          id  tit                         gen            new_gen
      0  620  AAA  [Romance, Satire, Fiction]                 []
      1  843  BBB    [Science Fiction, Novel]  [Science Fiction]
      2  986  CCC            [Mystery, Novel]          [Mystery]
      

      【讨论】:

      • @Nyxdia 很高兴它有帮助。编码快乐..!!
      猜你喜欢
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 2021-10-30
      • 2023-03-29
      • 1970-01-01
      • 2019-08-22
      相关资源
      最近更新 更多