如何在Pandas中删除包含问号(?)的行?
我正在尝试清理一些包含问号的数据。
我试着用:
df_census_new = df_census[~df_census.astype(str).apply(lambda row: row.str.contains("\?").any(), axis=1)]
但是出现了这个错误:
AttributeError: 只能对字符串值使用 .str 访问器
我本来想删除那些包含问号 (?) 的行。
1 个回答
0
你的列里面包含 ?
的数据必须是字符串类型。所以,最好的方法是使用 str.contains()
,可以这样写:
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', '?David', 'Eve'],
'Age': [25, 30, 35, '?', 45],
'Income': [50000, 60000, '?', 80000, 90000],
'City': ['New York', '?', 'Los Angeles', 'Chicago', 'Houston']
}
df_census = pd.DataFrame(data)
也就是说:
Name Age Income City
0 Alice 25 50000 New York
1 Bob 30 60000 ?
2 Charlie 35 ? Los Angeles
3 ?David ? 80000 Chicago
4 Eve 45 90000 Houston
这样可以得到:
string_columns = df_census.select_dtypes(include='object').columns
df_census_new = df_census[~df_census[string_columns].apply(lambda x: x.str.contains('\?', regex=True)).any(axis=1)]
结果是:
Name Age Income City
0 Alice 25 50000 New York
4 Eve 45 90000 Houston