使用.loc查询非空值和仅字符串值

2024-05-18 21:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图查询一个dataframe来删除所有的空值和数值(int,float)值。在

我的数据帧:

make_df = ["Hello", "World", "abcd", 12.4, np.nan,  "qwerty123"]
df = pd.DataFrame(make_df, columns = ["col1"])

我的代码:

^{pr2}$

到目前为止,我所能做的就是删除DataFrame中的空值,但不能删除数值。在

请帮忙。在


Tags: 数据hellodataframedfworldmakenpnan
2条回答

另一种方法是用0填充NaN,并使用^{}过滤掉数字:

df.loc[pd.to_numeric(df.col1.fillna(0),errors='coerce').isna(),'col1']

^{pr2}$

^{}errors='coerce'一起使用,测试不丢失值与测试不丢失值链接:

df1 = df[pd.to_numeric(df["col1"], errors='coerce').isna() & df["col1"].notna()]

或者,如果需要区分数值和数值的字符串表示形式,可以通过isinstance进行测试:

^{pr2}$
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

相关问题 更多 >

    热门问题