【问题标题】:Filtering a column of mixed types and objects过滤混合类型和对象的列
【发布时间】:2019-05-01 18:20:59
【问题描述】:

我有一个数据框:

NPI.         hcps_code 
1003000126     92300
1003000126     G0101
1003000126.    H0002

它有 27 个其他功能和大约 900 万行,在“hcps_code”列中有混合数据类型,其中一些是整数,一些是字符串,或者它们是组合的。

我需要根据匹配的数据框过滤数据框:

A) 适合 92920 到 93799 的范围

B) 匹配代码“H0002”或“G0101”

到目前为止,我已经尝试过:

Surg_mammo_DA = super_clean_df.query('hcpcs_code == G0101')

但得到错误:

UndefinedVariableError: name 'G0101' is not defined

接下来我试试:

Surg_mammo_DA = super_clean_df.filter(like='H0002', axis=0)

这将返回一个空数据框,因为该列的 dtype 是它无法识别的对象。

最后我试试:

Surg_mammo_DA = super_clean_df.loc[(super_clean_df['hcpcs_code'] == 'H0002') &
                                  (super_clean_df['hcpcs_code'] == 'G0101')]

由于对象冲突,这也会返回一个空数据框。

所以我尝试更改列的 dtype:

super_clean_df.hcpcs_code = super_clean_df.hcpcs_code.astype(str)

但是它保持不变,很可能是因为特性中有一些值是 int 和 string/int 组合的:

hcpcs_code                           object

有谁知道如何根据一列的多个条件过滤数据集,并处理列中的不同数据类型?

【问题讨论】:

  • 检查你的列类型它是对象,所以Surg_mammo_DA = super_clean_df.query('hcpcs_code == "G0101"')
  • filters = df.hcps_code.between(92920 , 93799) | df.hcps_code.isin(['H0002', 'G0101']df[filters]?
  • 过滤器用于索引和列,而不用于值
  • @QuangHoang "TypeError: '>=' 在 'bytes' 和 'int' 的实例之间不支持"
  • @Wen-Ben "Surg_mammo_DA = super_clean_df.query('hcpcs_code == "G0101"')" 返回一个空数据框,我知道它存在的唯一原因是因为我可以手动查看它

标签: python pandas


【解决方案1】:

编写两个处理数据类型和过滤器的条件

cond1 = pd.to_numeric(df['hcps_code'], errors = 'coerce').between(92920, 93799)
cond2 = df['hcps_code'].isin(['H0002', 'G0101'])
df[(cond1) | (cond2)]



NPI.         hcps_code 

1003000126     G0101
1003000126.    H0002

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2015-07-27
    • 2020-03-04
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    相关资源
    最近更新 更多