Python Pandas - 使用校正文件进行数据校正

问题描述 投票:0回答:1
我通常有大型数据集,我需要纠正其中的一些特定值。

我想出了一个校正文件,其中我连续有各种条件,我需要根据这些条件更改值。

条件1条件2条件3价值1123xx2123yx5
现在我想在我的数据框中纠正它并想出类似的东西:

for index, val in KORR.iterrows():
df.loc[(df.Cond1==val.iloc[0])&(df.Cond2==val.iloc[1])&(df.Cond3==val.iloc[2]),"Value1"]=val.iloc[3]
所以我检查了校正文件的每一行并过滤了大 df 中的数据并校正了每个值。

即使我的校正文件只有 100 行,这还是相当慢......有更好的方法吗?

python pandas data-manipulation
1个回答
0
投票
您可以从矢量化操作中受益。

我们所做的是将初始数据集

df

 和校正文件 
KORR
 与 :
合并

data = { 'Cond1': [123, 123, 124], 'Cond2': ['x', 'y', 'x'], 'Cond3': ['x', 'x', 'y'], 'Value1': [1, 2, 3] } df = pd.DataFrame(data) corrections = { 'Cond1': [123, 123], 'Cond2': ['x', 'y'], 'Cond3': ['x', 'x'], 'NewValue': [2, 5] } KORR = pd.DataFrame(corrections) df_corrected = pd.merge(df, KORR, how='left', on=['Cond1', 'Cond2', 'Cond3']) print(df_corrected) Cond1 Cond2 Cond3 Value1 NewValue 0 123 x x 1 2 1 123 y x 2 5 2 124 x y 3 NaN

how='left'

 函数中使用 
pd.merge()
 参数意味着合并的数据帧将包含左侧数据帧 
df
 中的所有行以及两个数据帧中的列。

使用

on=['Cond1', 'Cond2', 'Cond3']

 参数意味着,如果 on 参数指定的列中有匹配项,则右侧数据帧 
KORR
 中的行将添加到左侧数据帧中的行。如果没有匹配项,右侧数据帧中的新列将包含这些行的 NaN 值。

然后,如果

Value1

中的值不是
NewValue
,我们将其替换为
NaN
中的值(感谢
.combine_first(df_corrected['Value1'])
):

df_corrected['Value1'] = df_corrected['NewValue'].combine_first(df_corrected['Value1']) print(df_corrected) Cond1 Cond2 Cond3 Value1 NewValue 0 123 x x 2 2 1 123 y x 5 5 2 124 x y 3 NaN
最后我们用 :

删除

NewValue

df_corrected.drop(columns='NewValue', inplace=True) print(df_corrected) Cond1 Cond2 Cond3 Value1 0 123 x x 2 1 123 y x 5 2 124 x y 3
真的,你需要 3 行:

df_corrected = pd.merge(df, KORR, how='left', on=['Cond1', 'Cond2', 'Cond3']) df_corrected['Value1'] = df_corrected['NewValue'].combine_first(df_corrected['Value1']) df_corrected.drop(columns='NewValue', inplace=True)
    
© www.soinside.com 2019 - 2024. All rights reserved.