Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get get the value of a cell & store into variable with Pandas?

Tags:

python

pandas

I have a dataframe with latitude and longitude stored.

I am doing a for loop where I need to take the values of the current row contained within each and store as variables I can then use to do some geocoding work with.

If I do something like:

for r in df:
latitude = df['latitude']

This returns the latitude WITH the index. How do I just get the value without the index so I can do the work I need within the loop?

like image 395
Jeff Avatar asked Dec 13 '22 15:12

Jeff


2 Answers

The following should work:

latitude = latitude.values[0]

.values accesses the numpy representation of a pandas.DataFrame Assuming your code latitude = df['latitude'] really results in a DataFrame of shape (1,1), then the above should work.

like image 182
tobsecret Avatar answered Jan 04 '23 23:01

tobsecret


import pandas as pd

# Create a dataframe
df = pd.DataFrame([
                   {'First':'Bill'
                    ,'Last':'Thompson'
                    ,'AcctNum':'0001'
                   ,'AcctValue':100},
                   {'First':'James'
                    ,'Last':'Winters'
                    ,'AcctNum':'0002'
                    ,'AcctValue':200},
                   {'First':'Anna'
                    ,'Last':'Steele'
                    ,'AcctNum':'0003'
                    ,'AcctValue':300},
                   {'First':'Sean'
                    ,'Last':'Reilly'
                    ,'AcctNum':'0004'
                    ,'AcctValue':400}
                   ])

# Select data and set it to a variable
account_value = df.loc[df['AcctNum'] == '0003']['AcctValue'].values[0]
print account_value
like image 44
Justin Malinchak Avatar answered Jan 04 '23 22:01

Justin Malinchak