Python Forum
comparing columns - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: comparing columns (/thread-38951.html)



comparing columns - arvin - Dec-13-2022

I want to compare two columns.
If the values in column A is present in column B then the values should copy in column C with any special symbol in front
and if the values in column A is not present in column B then only that values should copy in column C without any special symbol in front.

Help! Sad


RE: comparing columns - paul18fr - Dec-13-2022

if you want to get some advices, you should be more precise, and even show an example.


RE: comparing columns - arvin - Dec-14-2022

[Image: Capture.png]


RE: comparing columns - paul18fr - Dec-14-2022

Initially I was thinking in something more complecated (entire column concern), but here, it seems you're working row by row: so I do not see any difficulty using at least "if ... then ... else".


RE: comparing columns - snippsat - Dec-14-2022

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.


RE: comparing columns - paul18fr - Dec-14-2022

@snippsat: Pandas nor speed were originaly in the scope (first post); if so, I would have proposed the vectored form suggesting np.equal and np.where for instance.

In any way I'm wondering if he/she is asking for advices or asking somebody to do the job for him/her