如何从 pandas 数据框中获取单个值作为字符串 [英] How to get a single value as a string from pandas data frame
问题描述
我正在从数据框查询一个似乎是'dtype:object'的值.我只想按原样打印值,而不打印索引或其他信息.我该怎么做?
I am querying a single value from my data frame which seems to be 'dtype: object'. I simply want to print the value as it is with out printing the index or other information as well. How do I do this?
col_names = ['Host', 'Port']
df = pd.DataFrame(columns=col_names)
df.loc[len(df)] = ['a', 'b']
t = df[df['Host'] == 'a']['Port']
print(t)
输出:
预期输出: b
推荐答案
如果可以保证只返回一个结果,请使用loc
并调用item
:
If you can guarantee only one result is returned, use loc
and call item
:
>>> df.loc[df['Host'] == 'a', 'Port'].item()
'b'
或者类似地,
>>> df.loc[df['Host'] == 'a', 'Port'].values[0]
'b'
...以获取 first 值(类似地,第二个为.values[1]
).哪个优于df.loc[df['Host'] == 'a', 'Port'][0]
,因为如果您的DataFrame如下所示,
...to get the first value (similarly, .values[1]
for the second). Which is better than df.loc[df['Host'] == 'a', 'Port'][0]
because, if your DataFrame looks like this,
Host Port
1 a b
然后将引发"KeyError:0" —
Then "KeyError: 0" will be thrown—
df.loc[df['Host'] == 'a', 'Port'][0]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
或者,使用at
:
>>> df.at[df['Host'].eq('a').idxmax(), 'Port']
'b'
缺点是如果'a'不存在,idxmax
将返回第一个索引(并返回错误的结果).
The drawback is that if 'a' doesn't exist, idxmax
will return the first index (and return an incorrect result).
这篇关于如何从 pandas 数据框中获取单个值作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!