pandas 数据框中的多列(绝对、百分比和分类)数据操作

Data Manipulation in multiple columns(absolute, percentage, and categorical) in pandas dataframe

我需要做一个函数,将输入作为数据框,字典{"Col_1" :% change,"Col_2":absolute change,"Col_3" : 0/1(Categorical)} 它应该对数据框进行更改。

我有这样的数据框

Date col_1 col_2 col_3
01/01/2022 90 100 0
01/02/2022 80 110 1
01/03/2022 92 120 0
01/04/2022 96 130 0
01/05/2022 99 150 1
01/06/2022 105 155 1

现在我传字典说,

{"Date":["01/01/2022","01/02/2022"],"col_1":[-10,-10],"col_2":10,"col_3":[1,0]}

那么我想要的效果会是这样

Date col_1 col_2 col_3
01/01/2022 81 10 1
01/02/2022 72 10 0
01/03/2022 92 120 0
01/04/2022 96 120 0
01/05/2022 99 150 1
01/06/2022 105 155 1

我跟着试过这个代码:

def per_change(df,cols,d):
    df[cols] = df[cols].add(df[cols].div(100).mul(pd.Series(d)), fill_value=0)
    return df

但没有成功。请帮忙!!

您可以使用 dic["Date"] 作为布尔掩码并使用 dic 中其他键下的值更新 df 中的值:

msk = df['Date'].isin(dic['Date'])
df.loc[msk, 'col_1'] *= (1 + np.array(dic['col_1']) / 100)
df.loc[msk, 'col_2'] = dic['col_2']
df.loc[msk, 'col_3'] = dic['col_3']

输出:

         Date  col_1  col_2  col_3
0  01/01/2022   81.0     10      1
1  01/02/2022   72.0     10      0
2  01/03/2022   92.0    120      0
3  01/04/2022   96.0    130      0
4  01/05/2022   99.0    150      1
5  01/06/2022  105.0    155      1