2015-10-08 349 views
5

返回單個單元格的值我想問一個問題,那就是在這個線程的擴展:從熊貓數據框中

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

df.loc [DF [ 'd'] = = 14] [COLNAME]或df.loc [DF [ 'd'] == 14] .values [index] –

回答

5

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

太棒了。非常感謝你們兩位。 – Nick