Pandas: Update Column Values from Another Column If Criteria

Updating a column in a Pandas DataFrame based on a condition of another column

If you know your colors before-hand, you could use masking with DataFrame.where and str.join to get this done.

v = pd.DataFrame(
np.repeat([['red;', 'blue;']], len(df), axis=0),
columns=df.columns,
index=df.index
)
df['msg'] = v.where(df.applymap(len) > 0, '').agg(''.join, axis=1)
df
A B msg
0 x x red;blue;
1 x blue;
2 x red;
3

assign one column value to another column based on condition in pandas

Based on the answers to this similar question, you can do the following:

  • Using np.where:

    df['column2'] = np.where((df['column2'] == 'Null') | (df['column2'] == 0), df['column1'], df['column2'])
  • Instead, using only pandas and Python:

    df['column2'][(df['column2'] == 0) | (df['column2'] == 'Null')] = df['column1']

update pandas dataframe column with value from another dataframe with condition

Let's try map instead:

to_map = df2[df2.week==1].set_index('team')['score']

to_update = df1.week==1

df1.loc[to_update, 'score1'] = df1.loc[to_update,'team1'].map(to_map)
df1.loc[to_update, 'score2'] = df1.loc[to_update,'team2'].map(to_map)

Output:

   week team1 team2 score1 score2
0 1 aa hh 24 10
1 1 bb ii 27 3
2 2 cc jj
3 1 dd kk 7 20
4 1 ee ll 9 13
5 1 ff mm 20 19
6 2 gg nn


Related Topics



Leave a reply



Submit