Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何根据特定条件替换Dataframe中特定列的特定值?_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 3.x 如何根据特定条件替换Dataframe中特定列的特定值?

Python 3.x 如何根据特定条件替换Dataframe中特定列的特定值?,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,我有一个熊猫数据框,其中包含学生和他们获得的分数百分比。有些学生的分数超过100%。显然,这些值是不正确的,我想用NaN替换所有大于100%的百分比值 我已经试过一些代码,但不能完全得到我想要的 import numpy as np import pandas as pd new_DF = pd.DataFrame({'Student' : ['S1', 'S2', 'S3', 'S4', 'S5'], 'Percentages' : [85, 7

我有一个熊猫数据框,其中包含学生和他们获得的分数百分比。有些学生的分数超过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

正如您所看到的,这种代码是有效的,但它实际上替换了百分比大于100×NaN的特定行中的所有值。我只想将百分比列中的值替换为大于100的NaN。有什么方法可以做到这一点吗?

尝试使用:


而且

或者

df.Percentages=df.Percentages.where(df.Percentages您可以使用:

输出:

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

这也会起作用。:)但是,如果可以,请避免应用,这会很慢。同意@anky_91,尝试避免
。如果不需要,请应用
。这已经存在于我的解决方案中(检查注释部分)现在不确定这有什么不同:)@JohnE是的,也取决于df的大小,我认为?对于较大的dfs,不应使用np。哪里的工作速度更快?BDW现在未注释。:)谢谢你,我想你是对的。通常
np。其中
非常快。
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)
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)