pandas 根据另一列值替换panda Dataframe 中的列值

7xzttuei  于 2023-04-04  发布在  其他
关注(0)|答案(5)|浏览(172)

我有以下的Pandasdataframe:

Material    Min_lot      Reorder
0   E01            1            0
1   E02            1            -1
2   E03            1            10
3   E04            1            1
4   E05            5            0
5   E06            5            -1
6   E07            5            10
7   E08            5            5
8   E09            5            3

我想根据以下规则创建新列或替换现有的重新排序

reorder <0 replace reorder with 0
reorder >= Min_lot -> do not change reorder
reorder < Min_lot  -> replace reorderwith Min_lot value

作为示例,输出是:

lc8prwob

lc8prwob1#

df['Reorder'] = df[['Min_lot', 'Reorder']].max(axis = 1) * (df['Reorder'] > 0)
r1wp621o

r1wp621o2#

合并clipmask

df['Reorder'] = (df['Reorder'].clip(df['Min_lot'])
                 .mask(df['Reorder'].lt(0), 0)
                )

输出:

Material  Min_lot  Reorder
0      E01        1        1
1      E02        1        0
2      E03        1       10
3      E04        1        1
4      E05        5        5
5      E06        5        0
6      E07        5       10
7      E08        5        5
8      E09        5        5

给定输出,掩码条件应该是〈= 0:

df['Reorder'] = (df['Reorder'].clip(df['Min_lot'])
                 .mask(df['Reorder'].le(0), 0)
                )

输出:

Material  Min_lot  Reorder
0      E01        1        0
1      E02        1        0
2      E03        1       10
3      E04        1        1
4      E05        5        0
5      E06        5        0
6      E07        5       10
7      E08        5        5
8      E09        5        5
xoefb8l8

xoefb8l83#

我想你们都有条件了,你们所要做的就是按顺序做:

df['New_Reorder'] = df['Reorder']
m = df['Reorder'].lt(df['Min_lot'])
df.loc[m, 'New_Reorder'] = df.loc[m, 'Min_lot']
df.loc[df['Reorder'].le(0), 'New_Reorder'] = 0

print(df)

  Material  Min_lot  Reorder  New_Reorder
0      E01        1        0            0
1      E02        1       -1            0
2      E03        1       10           10
3      E04        1        1            1
4      E05        5        0            0
5      E06        5       -1            0
6      E07        5       10           10
7      E08        5        5            5
8      E09        5        3            5
x759pob2

x759pob24#

你可以使用np.where函数,它就像Excel的嵌套if公式一样。我按照你写的顺序应用公式。

df['New_Reorder ']=np.where(df.Reorder〈0,0,np.where(DF.Reorder〈df.Min_lot,ff.Min_lot,df.Reorder))

xjreopfe

xjreopfe5#

可以使用apply()方法:

df['New_Reorder'] = df.apply(lambda row: max(0, row['Min_lot']) if row['Reorder'] < row['Min_lot'] else row['Reorder'], axis=1)

相关问题