Pandas忽略非数字值

时间:2017-04-23 10:30:43

标签: python pandas

我有这个df:

     X
0   13500
1   13600
2   BBOX-001
3   Mobi-1
4   15003
5   15004

我正在尝试输入新列。如果x> 15000则值为A,否则为B.如果X为非数字(BBOX-001,Mobi-1),则应显示X列中的值:

     X        Y
0   13500     B
1   13600     B
2   BBOX-001  BBOX-001
3   Mobi-1    Mobi-1
4   15003     A
5   15004     A

我在下面有这个,但如何忽略X列中的非数字值?

df['Y'] = np.where(df['X'] > 15000, 'A', 'B')

2 个答案:

答案 0 :(得分:2)

df['X']包含数字和字符串的混合时,列的dtype将为object而不是数字dtype。 df['X']中的类似数字的项目可能是整数或浮点数,甚至可能是字符串(从您的问题中不清楚)。 在这种情况下,许多数字操作(如df['X'] > 15000)可能会引发错误。

要将类似数字的值视为数字,请使用pd.to_numeric将列转换为数字dtype:

In [41]: numeric_X = pd.to_numeric(df['X'], errors='coerce')
In [43]: numeric_X
Out[43]: 
0    13500.0
1    13600.0
2        NaN
3        NaN
4    15003.0
5    15004.0
Name: X, dtype: float64

您还可以通过测试NaN来识别类似字符串的值:

is_stringlike = np.isnan(numeric_X)
import numpy as np
import pandas as pd

df = pd.DataFrame({'X': ['13500', '13600', 'BBOX-001', 'Mobi-1', '15003', '15004']})

numeric_X = pd.to_numeric(df['X'], errors='coerce')
is_stringlike = np.isnan(numeric_X)
conditions = [numeric_X > 15000, is_stringlike]
choices = ['A', df['X']]
df['Y'] = (np.select(conditions, choices, default='B'))
print(df)

产量

          X         Y
0     13500         B
1     13600         B
2  BBOX-001  BBOX-001
3    Mobi-1    Mobi-1
4     15003         A
5     15004         A

答案 1 :(得分:1)

您可以使用if

实现目标
convert_objects

输出:

import pandas as pd
import numpy as np

df = pd.DataFrame({'X': ['13500', '13600', 'BBOX-001', 'Mobi-1', '15003', '15004']})
# Convert only numeric value to put it in comparison
df['Y'] = np.where(df.X.convert_objects(convert_numeric=True) > 15000, 'A', 'B')

print (df)
相关问题