简体   繁体   中英

How do I get get the value of a cell & store into variable with 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?

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.

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

You can Try something like this. This works for me. DF.iloc[2].Name

Here 2 is the row , and the Name is the column name. You can do an iteration in while loop after that.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM