过滤列中的字符串/浮点数/整数值(Pandas)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45338209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering string/float/interger values in columns (Pandas)
提问by MMM
How can I filter only string values / integer / float values in one column in pandas data frame like below?
如何在如下所示的Pandas数据框中的一列中仅过滤字符串值/整数/浮点值?
SIC
1 246804
2 135272
3 898.01
4 3453.33
5 shine
6 add
7 522
8 Nan
9 string
10 29.11
11 20
回答by Scott Boston
You can use the outputs from pd.to_numeric
and boolean indexing.
您可以使用pd.to_numeric
布尔索引的输出。
To get only the strings use:
要仅获取字符串,请使用:
df[pd.to_numeric(df.SIC, errors='coerce').isnull()]
Output:
输出:
SIC
5 shine
6 add
8 Nan
9 string
To get only the numbers use:
要仅获取数字,请使用:
df[pd.to_numeric(df.SIC, errors='coerce').notnull()]
Output:
输出:
SIC
1 246804
2 135272
3 898.01
4 3453.33
7 522
10 29.11
11 20
回答by nanojohn
You can use the apply()
method along with the isinstance()
function. Can replace str
with int
, float
, etc:
您可以将apply()
方法与isinstance()
函数一起使用。可取代str
用int
,float
等:
df = pd.DataFrame([1,2,4.5,np.NAN,'asdf',5,'string'],columns=['SIC'])
print(df)
SIC
0 1
1 2
2 4.5
3 NaN
4 asdf
5 5
6 string
print(df[df['SIC'].apply(lambda x: isinstance(x,str))])
SIC
4 asdf
6 string