【问题标题】:Find globally unique elements from lists within dataframe从数据框中的列表中查找全局唯一元素
【发布时间】:2021-06-30 07:14:59
【问题描述】:

我有一个包含一列术语的数据框,例如:

In [2]: df = pd.DataFrame(
  ...:     [
  ...:         [123, ["D2334","D7645","D0938","D00001"]],
  ...:         [223, ["A938","D00001","D0938"]],
  ...:         [342, ["B983","D2334"]],
  ...:     ],
  ...:     columns=['ID', 'terms'],
  ...: ).set_index('ID')

In [3]: df
Out[3]:
                             terms
ID
123  [D2334, D7645, D0938, D00001]
223          [A938, D00001, D0938]
342                  [B983, D2334]

我想为每个 ID 获取一个全局唯一的术语列表,即:

ID       terms
123  ["D7645"]
223   ["A938"]
342   ["B983"]

例如,我想删除“D2334”,因为它存在于两个或多个 ID ...

【问题讨论】:

  • 参见How much researchQuestion Checklist。你需要“融化”或“爆炸”你的行,然后找到独特的元素。每一个都是一个简单的查找。
  • 嗨 - 欢迎来到堆栈溢出! @Prune 确实建议了一些需要检查的好东西。一般来说,他们指出 Pandas 并不是真正为处理数据帧中的列表而设计的,因此使用 pd.explode 可能会有所帮助。不过,这也可能会破坏你的记忆。
  • @MichaelDelgado 用户已更改 df 创建,但注意到有时列表被读取为字符串,具体取决于您导入它们的方式...

标签: python python-3.x pandas


【解决方案1】:

例如,如果您从 csv 导入,您可能会使用 str 类型而不是列表:

import pandas as pd
import ast

test_df = pd.read_csv('test_df.csv', sep=';')

if isinstance(test_df.iloc[0]['terms'], str): # check type of record terms 
    print(type(test_df.iloc[0]['terms']))
    test_df['terms'] = test_df['terms'].apply(ast.literal_eval)

test_df = test_df.explode('terms', ignore_index=True)
test_df.drop_duplicates(subset=['terms', ], keep=False, inplace=True)


print(test_df)

输出:

<class 'str'>
    ID  terms
1  123  D7645
4  223   A938
7  342   B983

不完全是您的输出,但我的猜测是您可能更喜欢将术语放在 str 而不是括号之间。

参考:

cast str to tuple/list

pd.explode doc

【讨论】:

    【解决方案2】:

    您可以通过堆叠值将所有列表元素折叠到单个 numpy 数组中:

    all_terms = np.hstack(df.terms.values)
    

    然后您可以使用 numpy 的 unique 来查找所有唯一术语,以及它们的频率,并限制仅出现一次的唯一术语:

    unique, counts = np.unique(all_terms, return_counts=True)
    unique_with_only_one_appearance = unique[counts == 1]
    

    最后,听起来您正在尝试过滤这些术语以仅包含这些独特的术语:

    df['unique_terms'] = df.terms.apply(lambda x: [i for i in x if i in unique_with_only_one_appearance])
    

    这不是一个非常有效的工作流程,如果您正在处理除 pandas 之外的大量令牌集,则可能有更好的方法来组织您的数据。您可以随时查看Software Recommendations 堆栈交换站点,了解有关用于此类数据集的工具的提示。

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 2016-01-12
      • 2020-03-09
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多