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
Robot Framework Using Python, Key Press Without Selecting Any Button or Element in the Page
How to Convert List into String With Quotes in Python
Python-Compare Two String Columns in Same Dataframe, Return Matching Result
Pip3: Command Not Found But Python3-Pip Is Already Installed
How to Remove Unused Packages from Virtualenv
Python: How to Split a List Based on a Specific Element
Why Is This Python Script With Matplotlib So Slow
Access Is Denied When Trying to Pip Install a Package on Windows
Keeping High Scores in a Text File
How to Extract Text from an Existing Docx File Using Python-Docx
How to Connect to a Remote Windows Machine to Execute Commands Using Python
Changing Presence Discord Status
Iterate Over Worksheets, Rows, Columns
How to Find Consecutive Numbers in a Python List
Read Multiple Images on a Folder in Opencv (Python)
Find Matching Rows in 2 Dimensional Numpy Array