我的数据框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所述的方法在“从”和“到”列中过滤出None值:

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

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


但这是行不通的,所有值都保持不变。
我使用错了吗,还是有更好的方法呢?

最佳答案

使用它,因为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")]

10-02 06:40