您可以使用loc http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html + values http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html用于转换Serie
to numpy array
然后选择第一个值[0]
:
print (df.loc[df.name == 'george', 'age'].values)
[23]
print (df.loc[df.name == 'george', 'age'].values[0])
23
或者简单地选择第一个值Series
with iloc http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html:
print (df.loc[df.name == 'george', 'age'].iloc[0])
23
或者选择第一项iat http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iat.html:
print (df.loc[df.name == 'george', 'age'].iat[0])
23
Or use Series.item http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.item.html:
print (df.loc[df.name == 'george', 'age'].item())
23
如果可能没有匹配值,则上述解决方案失败。
那么就可以使用next
with iter
trick:
print (next(iter(df.loc[df.name == 'george', 'age']),'no match value'))
23
print (next(iter(df.loc[df.name == 'jano z hornej dolnej', 'age']),'no match value'))
no match value