从 Pandas DataFrame 返回单个单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33027643/
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
Return single cell value from Pandas DataFrame
提问by Nick
I would like to ask an question that is an extension on this thread:
我想问一个问题,这是这个线程的扩展:
Select rows from a DataFrame based on values in a column in pandas.
根据 pandas 中列中的值从 DataFrame 中选择行。
The code from this thread is listed below:
下面列出了该线程中的代码:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['D'] == 14])
This will yield the following result:
这将产生以下结果:
A B C D
7 foo three 7 14
Based on the code above, how can I return a single 'value' not a row. That is, how can I return the value '7'or value 'foo'as opposed to the entire row?
根据上面的代码,我怎样才能返回一个“值”而不是一行。也就是说,我如何返回值'7'或值'foo'而不是整行?
回答by Leb
@JonahWilliams was close, here's a working one:
@JonahWilliams 很接近,这是一个有效的:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df.loc[df['D'] == 14]['A'].index.values)
>>>[7]
print(df.loc[df['D'] == 14]['A'].values)
>>>['foo']

