pandas 如何从熊猫数据框中获取单个值作为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53255796/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:08:56  来源:igfitidea点击:

How to get a single value as a string from pandas data frame

pythonpandasnumpy

提问by Oamar Kanji

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?

我正在从我的数据框中查询一个似乎是“dtype: object”的值。我只是想按原样打印值,而不打印索引或其他信息。我该怎么做呢?

col_names = ['Host', 'Port']
df = pd.DataFrame(columns=col_names)
df.loc[len(df)] = ['a', 'b']

t = df[df['Host'] == 'a']['Port']
print(t)

OUTPUT: enter image description here

输出: 在此处输入图片说明

EXPECTED OUTPUT: b

预期产出:b

回答by cs95

If you can guarantee only one result is returned, use locand call item:

如果您可以保证只返回一个结果,请使用loc并调用item

>>> df.loc[df['Host'] == 'a', 'Port'].item()
'b'

Or, similarly,

或者,类似地,

>>> df.loc[df['Host'] == 'a', 'Port'].values[0]
'b'

...to get the firstvalue (similarly, .values[1]for the second). Which is better than df.loc[df['Host'] == 'a', 'Port'][0]because, if your DataFrame looks like this,

...获得第一个值(类似地,.values[1]第二个)。这比df.loc[df['Host'] == 'a', 'Port'][0]因为如果你的 DataFrame 看起来像这样更好,

  Host Port
1    a    b

Then "KeyError: 0" will be thrown—

然后会抛出“KeyError: 0”——

df.loc[df['Host'] == 'a', 'Port'][0]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)


Alternatively, use at:

或者,使用at

>>> df.at[df['Host'].eq('a').idxmax(), 'Port']
'b'

The drawback is that if 'a' doesn't exist, idxmaxwill return the first index (and return an incorrect result).

缺点是如果 'a' 不存在,idxmax将返回第一个索引(并返回不正确的结果)。

回答by Karn Kumar

it should work simply..

它应该简单地工作..

>>> df
  Host Port
0    a    b
>>> df[df['Host'] == 'a']['Port'][0]   # will choose the first index simply which is 'b'
'b'

OR, use with print which will strip off the surrounded single ticks.

或者,与 print 一起使用,这将去除被包围的单个刻度。

>>> print(df[df['Host'] == 'a']['Port'][0])
b

This will easier because you have just choose the desired Index even if you have Multiple values across Portcolumns

这会更容易,因为即使跨Port列有多个值,您也只需选择所需的索引

Example:

例子:

>>> df
  Host Port
0    a    b
1    c    c

Looking for distinct a& cbased on Index:

寻找不同的a&c基于索引:

>>> df[df['Host'] == 'a']['Port'][0]
'b'
>>> df[df['Host'] == 'c']['Port'][1]
'c'

回答by PL200

As mentioned in my comment, using [1] should work afterwards, to pull the variable you're looking for.

正如我在评论中提到的,使用 [1] 应该可以在之后工作,以提取您正在寻找的变量。

t = df[df['Host'] == 'a']['Port'][1]