繁体   English   中英

如何替换pandas Dataframe中的非整数值?

[英]How to replace non integer values in a pandas Dataframe?

我有一个由两列组成的数据框,Age和Salary

Age   Salary
21    25000
22    30000
22    Fresher
23    2,50,000
24    25 LPA
35    400000
45    10,00,000

如何处理Salary列中的异常值并用整数替换它们?

如果需要替换非数字值,请使用带参数errors='coerce' to_numeric

df['new'] = pd.to_numeric(df.Salary.astype(str).str.replace(',',''), errors='coerce')
              .fillna(0)
              .astype(int)
print (df)
   Age     Salary      new
0   21      25000    25000
1   22      30000    30000
2   22    Fresher        0
3   23   2,50,000   250000
4   24     25 LPA        0
5   35     400000   400000
6   45  10,00,000  1000000

使用numpy在哪里找到非数字值,替换为'0'。

df['New']=df.Salary.apply(lambda x: np.where(x.isdigit(),x,'0'))

如果您使用Python 3,请使用以下内容。 我不确定其他Python版本如何返回类型(x)。 但是我不会用0替换缺失或不一致的值,最好用None替换它们。 但是,假设您要将字符串值(异常值或不一致的值)替换为0:

df['Salary']=df['Salary'].apply(lambda x: 0 if str(type(x))=="<class 'str'>" else x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM