簡體   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