Home > front end >  Is there a way to associate the value of a row with another row in Excel using Python
Is there a way to associate the value of a row with another row in Excel using Python

Time:10-12

I created a df from the data of my excel sheet and in a specific column I have a lot of values that are the same, but some of then are different. What I want to do is find in what row these different values are and associate each one with another value from the same row. I will give an example:

 ColA      ColB    
'Ship'      5
'Ship'      5
'Car'       3
'Ship'      5
'Plane'     2

Following the example, is there a way to find where the values different from 5 are with the code giving me the respective value from ColA? In this case would be finding 3 and 2, returning for me 'Car' and 'Plane', respectively.

Any help is welcome! :)

CodePudding user response:

It depends on exacty what you want to do, but you could use:

  • a filter - to filter for the value you seek.
  • .where - to show values which are False.

Given the above dataframe the following would work:

df['different'] = df['ColB']==5
df['type'] = df['ColA'].where(df['different']==False)
print(df)

Which returns this:

    ColA  ColB  different   type
0   Ship     5       True    NaN
1   Ship     5       True    NaN
2    Car     3      False    Car
3   Ship     5       True    NaN
4  Plane     2      False  Plane

The 4th column has what you seek...

  • Related