Home > OS >  Python Pandas: How to find element in a column with a matching string object of other column
Python Pandas: How to find element in a column with a matching string object of other column

Time:02-11

I have this string object:

code = '1002'

And i also have the following Pandas Data Frame:

pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

CodePudding user response:

Try:

df = pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})

code = '1002'
df.loc[df['Code'] == code, 'Place'].iloc[0]
Peru

Or

df[df['Code'] == code]['Place']

CodePudding user response:

basically to solve this u have to get the index of the code first, after converting data frame value into list, I think my following code might help u.

 import pandas as pd
 code = '1001'
 df = pd.DataFrame({'Code':['1001','1002','1003','1004'],
          'Place':['Chile','Peru','Colombia','Argentina']})

 code_index = list(df['Code']).index(code)
 print(code_index)
 area = df['Place'][code_index]
 print(area)

CodePudding user response:

You can use set_index first, if you want to get the actual value:

>>> df.set_index('Code').loc['1002', 'Place']
'Peru'
  • Related