从Pandas DataFrame返回单个单元格值

时间:2015-10-08 23:35:13

标签: python pandas

我想问一个问题是这个帖子的扩展名:

Select rows from a DataFrame based on values in a column in pandas

此线程的代码如下所示:

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])

这将产生以下结果:

   A    B      C   D
7  foo  three  7  14

根据上面的代码,我如何返回单个'值'不是一排。也就是说,如何返回值'7'或值'foo'而不是整行?

1 个答案:

答案 0 :(得分:8)

@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']