【问题标题】:Pandas filter or delete rows multiple conditionsPandas 过滤或删除行多个条件
【发布时间】:2018-06-20 21:42:38
【问题描述】:

我有这个数据框 boroughCounts 和这些样本值:

    From    To          Count
9   None    Manhattan   302
10  Bronx   Bronx       51
11  Bronx   Manhattan   244
12  None    Brooklyn    8
13  Bronx   Queens      100
14  None    None        67

尝试使用herehere 所述的这种方法过滤“From”和“To”列中的None 值:

boroughCounts = boroughCounts[(boroughCounts.From != None) & (boroughCounts.To != None)]

boroughCounts = boroughCounts[(boroughCounts["From"] != None) & (boroughCounts["To"] != None)]

但它不起作用,所有值都保持原样。 是我用错了,还是有更好的方法?

【问题讨论】:

  • boroughCounts.info() 返回什么?

标签: python pandas dataframe


【解决方案1】:

使用这个,因为 None 是一个字符串,你需要用 NaN 替换那个字符串:

df_out = boroughCounts.replace('None', np.nan).dropna()
df_out

输出:

     From         To  Count
10  Bronx      Bronx     51
11  Bronx  Manhattan    244
13  Bronx     Queens    100

或者您可以使用“无”来使用布尔索引:

boroughCounts[(boroughCounts.From != "None") & (boroughCounts.To != "None")]

【讨论】:

  • 使用“None”工作,感谢@Scott,似乎从RDD导入时它已转换为字符串!不确定
【解决方案2】:

检查您的数据框以了解类型。

boroughCounts.dtypes

这将告诉您他的 To 和 From 列是类型对象。这可能意味着它们都是字符串或字符串和 None 类型的组合。检查你的一个无。

type(boroughCounts.iloc[15].From)

这将显示第 15 行的 From 列中的 None 是否为字符串。如果是这样,您需要更改您的查询。

【讨论】:

  • 这些提示很有帮助
猜你喜欢
  • 2018-06-12
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2017-03-07
  • 1970-01-01
相关资源
最近更新 更多