• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Pandas replace values in columns based on condtion

Resolved: Pandas replace values in columns based on condtion

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have a dataframe like below:
dummy_df_dict  = {'Email':['joblogs@gmail.com', 'joblogs@gmail.com', 'johnsmith@gmail.com', 'johnsmith@gmail.com'],
              'Transaction_Country': ['CA', 'No Country Listed', 'No Country Listed', 'DE'],
             'Country_name': ['Canada', 'No Country Listed', 'No Country Listed', 'Germany'],
                       'Continent':['North America', 'No Contient listed', 'No Contient listed', 'Europe']}
    Email   Transaction_Country Country_name    Continent
0   joblogs@gmail.com   CA  Canada  North America
1   joblogs@gmail.com   No Country Listed   No Country Listed   No Contient listed
2   johnsmith@gmail.com No Country Listed   No Country Listed   No Contient listed
3   johnsmith@gmail.com DE  Germany Europe
I’m just trying to replace the “No “XYZ” listed text with the actual country / continent based on the email above / below.
So for example, the 2nd row [1] instead of showing ‘Transaction_Country’ as ‘No Country Listed’ it instead would be replaced with the value ‘CA’. And then on the next row, for johnsmith it would be replaced with “DE”.
Many thanks!

Answer:

df = df.replace('No Country Listed', np.nan).replace('No Contient listed', np.nan)
df = df.sort_values(['Email', 'Transaction_Country']).groupby('Email')[df.columns].ffill()
print(df)
Output:
                 Email Transaction_Country Country_name      Continent
0    joblogs@gmail.com                  CA       Canada  North America
1    joblogs@gmail.com                  CA       Canada  North America
3  johnsmith@gmail.com                  DE      Germany         Europe
2  johnsmith@gmail.com                  DE      Germany         Europe
Looking at it again, I think just this works as well:
df = df.replace('No Country Listed', np.nan).replace('No Contient listed', np.nan)
df = df.sort_values(['Email', 'Transaction_Country']).ffill()

If you have better answer, please add a comment about this, thank you!

pandas python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: linq2db throws exception when filtering by nested collection

02/04/2023

Resolved: Table data is coming as empty in React

02/04/2023

Resolved: In a Pinescript v5 Strategy why is my bool not working?

02/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.