【问题标题】:Pandas DataFrame list comparison for every row in a column列中每一行的 Pandas DataFrame 列表比较
【发布时间】:2015-05-13 11:33:17
【问题描述】:

我有一个数据框

In [3]: df
Out[3]:
                             Price  Size        Codes
2015-04-13 06:14:49-04:00  100.200   900     FT,R6,IS
2015-04-13 06:14:54-04:00  100.190   100     FT,R6,IS
2015-04-13 06:14:54-04:00  100.190   134     FT,R6,IS
2015-04-13 06:15:02-04:00  100.170   200     FT,R6,IS
...                            ...   ...          ...
[248974 rows x 3 columns]

还有一个列表

exclude = ['R6', 'F2', 'IS']

如果exclude 的其中一项在df 列下的df 行中,我想过滤掉该行。

我发现我可以做到这一点

In [4]: df.Codes.str.split(',')
Out[4]:
2015-04-13 06:14:49-04:00        [FT, R6, IS]
2015-04-13 06:14:54-04:00        [FT, R6, IS]
2015-04-13 06:14:54-04:00        [FT, R6, IS]
2015-04-13 06:15:02-04:00        [FT, R6, IS]
...
Name: Codes, Length: 248974

基本上我想要的是按照df[df.Codes.split(',') in exclude] 或类似的方式进行查询。非常感谢任何帮助。

【问题讨论】:

    标签: python list pandas


    【解决方案1】:
    # for the sake of performance, we turn the lookup list into a set
    excludes = set(['R7', 'R5'])
    
    ix = df.Codes.str.split(',').apply(lambda codes: not any(c in excludes for c in codes))
    df[ix] # returns the filtered DataFrame
    

    【讨论】:

    • 速度是原来的两倍
    【解决方案2】:
    df['check'] = df['Codes'].apply(lambda code: 1 if [elt for elt in code.split(',') if elt in exclude] else 0)
    df_filtered_out = df[df['check'] == 1]
    

    以防万一:apply() 默认逐行工作(查看 pandas 文档了解更多信息),if some_list 如果 some_list 为空则返回 False,否则返回 True。

    【讨论】:

    • 谢谢,这正是我所需要的
    猜你喜欢
    • 2018-11-18
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2017-05-14
    • 2021-08-24
    相关资源
    最近更新 更多