Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.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 基于列条件的fillna和replace_Python_Pandas_Conditional Statements_Fillna - Fatal编程技术网

Python 基于列条件的fillna和replace

Python 基于列条件的fillna和replace,python,pandas,conditional-statements,fillna,Python,Pandas,Conditional Statements,Fillna,我有一个带有MachineType、Prod/RT和其他几个列的df。MachineType包含TRUE或FALSE。需要.fillna和.replace,但对于MachineType有不同的方式。(正确和错误的填充值不同) 数据帧:updatedf 我的代码高于计算: updatedDf['Prod/RT']=updatedDf[updatedDf['MachineType']==True]['Prod/RT'].replace(np.inf,0.021660) updatedDf['Prod

我有一个带有MachineType、Prod/RT和其他几个列的df。MachineType包含TRUE或FALSE。需要.fillna和.replace,但对于MachineType有不同的方式。(正确和错误的填充值不同)

数据帧:updatedf

我的代码高于计算:

updatedDf['Prod/RT']=updatedDf[updatedDf['MachineType']==True]['Prod/RT'].replace(np.inf,0.021660)
updatedDf['Prod/RT']=updatedDf[updatedDf['MachineType']==True]['Prod/RT'].fillna(0.021660)


updatedDf['Prod/RT']=updatedDf[updatedDf['MachineType']==False]['Prod/RT'].replace(np.inf,0.050261)
updatedDf['Prod/RT']=updatedDf[updatedDf['MachineType']==False]['Prod/RT'].fillna(0.050261)
但是我的代码给出了一个带有Nan值的意外输出。有什么方法可以修复这个错误吗?或者我们不能用上面的方法。填充和。替换吗


我解决问题的方法是将填充和替换封装在函数中,并将其用作pandas
中的参数。apply()
。使用您的方法需要使用
.loc[]

updatedDf = pd.DataFrame({
    'MachineType' : np.random.choice([True, False], 10, True),
    'Prod/RT' : np.random.choice([np.nan, np.inf, random.random()], 10, True)
})

# solution 1
prod_RT_dict = {True:0.21660, False:0.050261}
def fillProd_RT(row):
    if row['Prod/RT'] != np.inf and pd.notna(row['Prod/RT']):
        return row['Prod/RT']
    else:
        return prod_RT_dict[row['MachineType']]
updatedDf['Prod/RT_2'] = updatedDf.apply(fillProd_RT, axis=1)

# solution 2
updatedDf['Prod/RT_3']=updatedDf['Prod/RT'].replace(np.inf,np.nan)
updatedDf.loc[updatedDf['MachineType']==True,'Prod/RT_3']=updatedDf\
    .loc[updatedDf['MachineType']==True,'Prod/RT_3'].fillna(0.021660)
updatedDf.loc[updatedDf['MachineType']==False,'Prod/RT_3']=updatedDf\
    .loc[updatedDf['MachineType']==False,'Prod/RT_3'].fillna(0.050261)

updatedDf

现在的问题是缺少关键信息,例如样本数据、样本输出。它很可能会被否决并关闭……请看:当然我会修复它的。看来你大部分时间都在那里。。。我建议使用
df.loc[mask,col]=df.loc[mask,col].fillna(…)
updatedf\.loc[updatedf['MachineType']==False,'Prod/RT_3'].fillna(0.050261)updatedf之后是什么意思?``是长单行代码的包装器。我加上它是因为我不想把那一行写在一行里。如果你不明白我的解释,请阅读