簡體   English   中英

如果未找到數據框列,則替換列值

[英]Replace a column value if it not found data-frame column

我是 python 的新手。 這里我有以下 dataframe 專欄,

  Predict
   100
   200
   2100
   2200
   51200
     0
   3600     

現在我有以下數組數據

cols = [100,156,160,162,200,256,262,2200,2600,2900,3600,4600]

現在,如果它不在預測中,我將嘗試用0替換它。

所以結果會像

predict
 100
 200
 0
2200
0
3600

現在我試過了

compare_df[~compare_df.isin(cols)] = 0

但我收到了這個錯誤

TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value

誰能幫我這個? 謝謝。

您必須使用Series而不是一列DataFrame通過選擇列名和loc來替換Predict的值:

compare_df.loc[~compare_df['Predict'].isin(cols), 'Predict'] = 0

如果使用列名刪除loc ,則通過掩碼將所有行設置為0 (如果存在):

compare_df[~compare_df['Predict'].isin(cols)] = 0

如果將 altarative 與numpy.where以及 select 列Predict一起使用:

compare_df['Predict'] = np.where(compare_df['Predict'].isin(cols),compare_df['Predict'], 0)

但在這里也可以工作:

compare_df['Predict'] = np.where(compare_df.isin(cols),compare_df, 0)

編輯:

比較需要列和列表中的相同類型,例如數字或對象(顯然是字符串)。

所以對於兩個字符串值都是必要的:

cols = [str(x) for x in cols]
compare_df.loc[~compare_df['Predict'].isin(cols), 'Predict'] = 0

或者對於兩個數字:

compare_df['Predict'] = compare_df['Predict'].astype(float)
compare_df.loc[~compare_df['Predict'].isin(cols), 'Predict'] = 0

如果無法通過.astype(float)轉換為浮點數:

compare_df['Predict'] = pd.to_numeric(compare_df['Predict'], errors='coerce')
compare_df.loc[~compare_df['Predict'].astype(float).isin(cols), 'Predict'] = 0

這是Series.where 它比np.where更好,因為你只需要在 cols 中不存在值時進行 0 的賦值。

new_df=df.where(df.isin(cols),0)
print(new_df)

   Predict
0      100
1      200
2        0
3     2200
4        0
5        0
6     3600

如果有超過 1 列:

new_df=df.copy()
new_df['Predict']=df['Predict'].where(df['Predict'].isin(cols),0)
print(new_df)
   Predict
0      100
1      200
2        0
3     2200
4        0
5        0
6     3600

如果他們有不同的類型:

new_df=df.copy()
new_df['Predict']=new_df['Predict'].astype(str) #this or the commented line depending on the type of cols and df ['Predict']
#new_df['predict']=new_df['Predict'].astype(int)
new_df['Predict']=df['Predict'].where(df['Predict'].isin(cols),0)
print(new_df)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM