簡體   English   中英

如何根據特定條件替換Pandas Dataframe中特定列的特定值?

[英]How to replace Specific values of a particular column in Pandas Dataframe based on a certain condition?

我有一個Pandas數據框,其中包含學生和他們獲得的分數百分比。 有些學生的分數顯示大於100%。 顯然這些值是不正確的,我想用NaN替換大於100%的所有百分比值。

我已經嘗試了一些代碼,但不能完全得到我想要的東西。

import numpy as np
import pandas as pd

new_DF = pd.DataFrame({'Student' : ['S1', 'S2', 'S3', 'S4', 'S5'],
                       'Percentages' : [85, 70, 101, 55, 120]})

#  Percentages  Student
#0          85       S1
#1          70       S2
#2         101       S3
#3          55       S4
#4         120       S5

new_DF[(new_DF.iloc[:, 0] > 100)] = np.NaN

#  Percentages  Student
#0        85.0       S1
#1        70.0       S2
#2         NaN      NaN
#3        55.0       S4
#4         NaN      NaN

正如您可以看到代碼類型的工作,但它實際上替換了NaN中Percentages大於100的特定行中的所有值。 我只想用NaN替換百分比列中的值,其中大於100.有沒有辦法做到這一點?

嘗試並使用np.where

new_DF.Percentages=np.where(new_DF.Percentages.gt(100),np.nan,new_DF.Percentages)

要么

new_DF.loc[new_DF.Percentages.gt(100),'Percentages']=np.nan

print(new_DF)

  Student  Percentages
0      S1         85.0
1      S2         70.0
2      S3          NaN
3      S4         55.0
4      S5          NaN

也,

df.Percentages = df.Percentages.apply(lambda x: np.nan if x>100 else x)

要么,

df.Percentages = df.Percentages.where(df.Percentages<100, np.nan)

你可以使用.loc

new_DF.loc[new_DF['Percentages']>100, 'Percentages'] = np.NaN

輸出:

  Student  Percentages
0      S1         85.0
1      S2         70.0
2      S3          NaN
3      S4         55.0
4      S5          NaN
import numpy as np
import pandas as pd

new_DF = pd.DataFrame({'Student' : ['S1', 'S2', 'S3', 'S4', 'S5'],
                      'Percentages' : [85, 70, 101, 55, 120]})
#print(new_DF['Student'])
index=-1
for i in new_DF['Percentages']:
    index+=1
    if i > 100:
        new_DF['Percentages'][index] = "nan"




print(new_DF)

暫無
暫無

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

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