Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparing columns
#5
Can do it like this.
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'col1': [1, 2, 3, 4, 10],
    'col2': [1, 4, 6, 8, 10]
    })

df['result'] = np.where(df['col1'] == df['col2'],  '*' + df['col2'].astype(str), df['col1'])

print(df)
Output:
col1 col2 result 0 1 1 *1 1 2 4 2 2 3 6 3 3 4 8 4 4 10 10 *10
(Dec-14-2022, 07:32 AM)paul18fr Wrote: so I do not see any difficulty using at least "if ... then ... else".
Pandas is very different beast🦄 and not like ordinary Python code,
so if use if/else or a for loop then are in most cases doing something wrong or very ineffective in Pandas.
Reply


Messages In This Thread
comparing columns - by arvin - Dec-13-2022, 12:34 PM
RE: comparing columns - by paul18fr - Dec-13-2022, 02:47 PM
RE: comparing columns - by arvin - Dec-14-2022, 05:05 AM
RE: comparing columns - by paul18fr - Dec-14-2022, 07:32 AM
RE: comparing columns - by snippsat - Dec-14-2022, 01:32 PM
RE: comparing columns - by paul18fr - Dec-14-2022, 01:54 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Comparing two columns with same value but different font format doug2019 1 788 Jan-08-2023, 02:58 PM
Last Post: Larz60+
  Comparing columns of Matrix stored in .txt files JoelFooCJ 2 2,334 Dec-11-2019, 07:21 AM
Last Post: JoelFooCJ

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020