pandas 在熊猫中单独打印一列的原始值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36261334/
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
Print the raw value of a column alone, in pandas?
提问by Richard
I have a dataframe:
我有一个数据框:
df = pd.DataFrame([ { 'name': 'george', 'age': 23 }, {'name': 'anna', 'age': 26}])
Now I want to retrive George's age:
现在我想检索乔治的年龄:
df[df.name == 'george'].age
But this outputs some extra information along with the raw value:
但这会输出一些额外的信息以及原始值:
0 23
Name: age, dtype: int64
How do I just get it to print 23
?
我怎样才能让它打印出来23
?
回答by jezrael
You can use loc
+ values
for converting Serie
to numpy array
and then select first value by [0]
:
您可以使用loc
+values
转换Serie
为numpy array
,然后通过[0]
以下方式选择第一个值:
print (df.loc[df.name == 'george', 'age'].values)
[23]
print (df.loc[df.name == 'george', 'age'].values[0])
23
Or simply select first value of Series
with iloc
:
或者简单地选择Series
with 的第一个值iloc
:
print (df.loc[df.name == 'george', 'age'].iloc[0])
23
Or select first item by iat
:
或通过iat
以下方式选择第一项:
print (df.loc[df.name == 'george', 'age'].iat[0])
23
Or use Series.item
:
或使用Series.item
:
print (df.loc[df.name == 'george', 'age'].item())
23
If possible no match value, above solutions failed.
如果可能没有匹配值,以上解决方案失败。
Then is possible use next
with iter
trick:
然后,可以使用next
与iter
招:
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
回答by jDo
Might as well make my comment an answer:
不妨让我的评论成为答案:
df[df.name == 'george'].age.values[0]
or
或者
int(df[df.name == 'george'].age)
should work
应该管用
回答by user1335606
df = [ { 'name': 'george', 'age': 23 }, {'name': 'anna', 'age': 26}]
k = [x['age'] for x in df if x['name'] == 'george']
print k