如何使用 Pandas 获取单元格的值并存储到变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51088585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get get the value of a cell & store into variable with Pandas?
提问by Jeff
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.
我正在做一个 for 循环,我需要获取每个包含的当前行的值并将其存储为变量,然后我可以使用它来进行一些地理编码工作。
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?
这将返回带有索引的纬度。我如何在没有索引的情况下获取值,以便我可以在循环中完成我需要的工作?
回答by tobsecret
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.
.values
访问 a 的 numpy 表示pandas.DataFrame
假设您的代码latitude = df['latitude']
确实产生了一个形状为 DataFrame 的数据帧(1,1)
,那么上面的应该可以工作。
回答by Justin Malinchak
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
回答by shrinivas madras
You can Try something like this. This works for me. DF.iloc[2].Name
你可以试试这样的。这对我有用。DF.iloc[2].名称
Here 2 is the row , and the Name is the column name. You can do an iteration in while loop after that.
这里 2 是行,而 Name 是列名。之后您可以在 while 循环中进行迭代。
Hope this helps.
希望这可以帮助。