我正在尝试查询数据框以删除所有空值和数字(int、float)值。
我的数据框:
make_df = ["Hello", "World", "abcd", 12.4, np.nan, "qwerty123"]
df = pd.DataFrame(make_df, columns = ["col1"])
我的代码:
df.loc[df["col1"].isna() == False]
到目前为止,我所能做的就是删除 DataFrame 中的空值,而不是数值。
请帮忙。
最佳答案
使用to_numeric
与 errors='coerce'
与测试不缺失值链接与测试不缺失值:
df1 = df[pd.to_numeric(df["col1"], errors='coerce').isna() & df["col1"].notna()]
如果需要区分数字和数值的字符串表示形式,可以通过 isinstance
进行测试:
df1 = df[~df['col1'].apply(lambda x: isinstance(x, (float, int)))]
print (df1)
col1
0 Hello
1 World
2 abcd
5 qwerty123
检查解决方案的差异 - 10
是数字的字符串表示:
make_df = ["Hello", "World", "abcd", 12.4, np.nan, "qwerty123", "10"]
df = pd.DataFrame(make_df, columns = ["col1"])
print (df)
col1
0 Hello
1 World
2 abcd
3 12.4
4 NaN
5 qwerty123
6 10
df1 = df[pd.to_numeric(df["col1"], errors='coerce').isna() & df["col1"].notna()]
print (df1)
col1
0 Hello
1 World
2 abcd
5 qwerty123
df2 = df[~df['col1'].apply(lambda x: isinstance(x, (float, int)))]
print (df2)
col1
0 Hello
1 World
2 abcd
5 qwerty123
6 10
关于python - 使用 .loc 查询非空值和仅字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56232702/