具有多个条件和计算的 Pandas 数据框

标签 pandas dataframe

我有以下 df.当满足 2 个条件时,需要将“数值”的值替换为“类型_1 的 4%”的计算:类型 = 类型_2 且数值 > 0

df_in = pd.DataFrame([['Jan-2021','P_1','Type_1','5'],['Jan-2021','P_1','Type_2','10'],['Jan-2021','P_1','Type_3','15'],
              ['Feb-2021','P_1','Type_1','7'],['Feb-2021','P_1','Type_2','0'],['Feb-2021','P_1','Type_3','21'],
                 ['Mar-2021','P_2','Type_1','3'],['Mar-2021','P_2','Type_2','6'],['Mar-2021','P_2','Type_3','9']],
                 columns = ['Month-Yr','Product','Type','Numerical'])

   Month-Yr Product Type    Numerical
0   Jan-2021    P_1 Type_1  5
1   **Jan-2021  P_1 Type_2  10**
2   Jan-2021    P_1 Type_3  15
3   Feb-2021    P_1 Type_1  7
4   **Feb-2021  P_1 Type_2  0**
5   Feb-2021    P_1 Type_3  21
6   Mar-2021    P_2 Type_1  3
7   **Mar-2021  P_2 Type_2  6**
8   Mar-2021    P_2 Type_3  9

预期结果:

     Month-Yr   Product Type    Numerical
0   Jan-2021    P_1 Type_1  5
1   **Jan-2021  P_1 Type_2  0.2**
2   Jan-2021    P_1 Type_3  15
3   Feb-2021    P_1 Type_1  7
4   Feb-2021    P_1 Type_2  0
5   Feb-2021    P_1 Type_3  21
6   Mar-2021    P_2 Type_1  3
7   **Mar-2021  P_2 Type_2  0.12**
8   Mar-2021    P_2 Type_3  9

最佳答案

一种选择是将数据翻转为水平形式,然后再计算条件,最后翻转回垂直形式;这应该比 for 循环更快,因为它是矢量化的并且依赖于 Pandas 方法:

# you can ignore this,
# if you are not fuzzy on the order
from pandas.api.types import CategoricalDtype
categories = CategoricalDtype(categories = df_in['Month-Yr'].unique(), 
                              ordered = True)
temp = (df_in
         # need the column as numbers
        .astype({'Numerical': int, 'Month-Yr':categories})
        .pivot(index=['Month-Yr', 'Product'], 
               columns='Type', 
               values='Numerical')
                # conditional statement here,
                # similar to python's if-else statement                 
        .assign(Type_2 = lambda df: np.where(df.Type_2 > 0,
                                             df.Type_1 * 0.04,
                                             df.Type_2))
        .stack()
        .reset_index(name='NUmerical')
      )


   Month-Yr Product    Type  Numerical
0  Jan-2021     P_1  Type_1       5.00
1  Jan-2021     P_1  Type_2       0.20
2  Jan-2021     P_1  Type_3      15.00
3  Feb-2021     P_1  Type_1       7.00
4  Feb-2021     P_1  Type_2       0.00
5  Feb-2021     P_1  Type_3      21.00
6  Mar-2021     P_2  Type_1       3.00
7  Mar-2021     P_2  Type_2       0.12
8  Mar-2021     P_2  Type_3       9.00

关于具有多个条件和计算的 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70614339/

相关文章:

python - 使用 Numpy 进行大数据集多项式拟合

具有分组依据和条件的 Python Pandas 新数据框列

Python有效地提取字典值并创建html页面

python - 如何将多个参数从 pandas 数据帧传递给函数并将结果返回到数据帧中特定位置的数据帧

python - 处理/转置 Pandas 数据框

python - pandas DataFrame如何使用groupby()来分割和组合数据

python - pandas 根据 "neighbours"删除行

pandas - 各组事件时间差异

python - 仅对带有 Pandas 的字符串列应用转换,忽略数字数据

python - 应用多个条件来选择当前行和前一行 - Pandas