pandas 如何从行和列引用返回数据框值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37700960/
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 to return a dataframe value from row and column reference?
提问by Andy
I know this is probably a basic question, but somehow I can't find the answer. I was wondering how it's possible to return a value from a dataframe if I know the row and column to look for? E.g. If I have a dataframe with columns 1-4
and rows A-D
, how would I return the value for B4
?
我知道这可能是一个基本问题,但不知何故我找不到答案。我想知道如果我知道要查找的行和列,如何从数据框中返回一个值?例如,如果我有一个包含列1-4
和行的数据框A-D
,我将如何返回值B4
?
回答by EdChum
You can use ix
for this:
您可以ix
为此使用:
In [236]:
df = pd.DataFrame(np.random.randn(4,4), index=list('ABCD'), columns=[1,2,3,4])
df
Out[236]:
1 2 3 4
A 1.682851 0.889752 -0.406603 -0.627984
B 0.948240 -1.959154 -0.866491 -1.212045
C -0.970505 0.510938 -0.261347 -1.575971
D -0.847320 -0.050969 -0.388632 -1.033542
In [237]:
df.ix['B',4]
Out[237]:
-1.2120448782618383
回答by jezrael
Use at
, if rows are A-D
and columns 1-4
:
使用at
,如果行A-D
和列1-4
:
print (df.at['B', 4])
If rows are 1-4
and columns A-D
:
如果行1-4
和列A-D
:
print (df.at[4, 'B'])
Fast scalar value getting and setting.
Sample:
样本:
df = pd.DataFrame(np.arange(16).reshape(4,4),index=list('ABCD'), columns=[1,2,3,4])
print (df)
1 2 3 4
A 0 1 2 3
B 4 5 6 7
C 8 9 10 11
D 12 13 14 15
print (df.at['B', 4])
7
df = pd.DataFrame(np.arange(16).reshape(4,4),index=[1,2,3,4], columns=list('ABCD'))
print (df)
A B C D
1 0 1 2 3
2 4 5 6 7
3 8 9 10 11
4 12 13 14 15
print (df.at[4, 'B'])
13