如果您可以保证只返回一个结果,请使用 loc
并调用 item
:
>>> df.loc[df['Host'] == 'a', 'Port'].item()
'b'
或者,同样地,
>>> df.loc[df['Host'] == 'a', 'Port'].values[0]
'b'
...要获取第一个值(同样,.values[1]
代表第二个值)。这比使用df.loc[df['Host'] == 'a', 'Port'][0]
更好,因为如果您的DataFrame如下所示,
Host Port
1 a b
这时将会抛出 "KeyError: 0" 异常
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
将返回第一个索引(并返回不正确的结果)。
FutureWarning: 'item' has been deprecated and will be removed in a future version
- user3521099df.Host.values
获取 Host 列的值列表,或者使用 df.Host.values[0]
和 df.Port.values[0]
获取字符串值。如果我错了,请纠正我,它对我有用。 - ferrumt = df['Host'].values[0]
将会给你第一个值。如果你需要一个字符串,只需这样做:
t = str(df['Host'].values[0])
它应该简单地工作。
>>> df
Host Port
0 a b
>>> df[df['Host'] == 'a']['Port'][0] # will choose the first index simply which is 'b'
'b'
或者,使用print函数,它会去掉被单引号包围的内容。
>>> print(df[df['Host'] == 'a']['Port'][0])
b
Port
列的情况下也是如此。
示例:
>>> df
Host Port
0 a b
1 c c
a
和c
。>>> df[df['Host'] == 'a']['Port'][0]
'b'
>>> df[df['Host'] == 'c']['Port'][1]
'c'
t = df[df['Host'] == 'a']['Port'][1]
t = df[df['Host'] == 'a']['Port'][0]
或者t = df[df['Host'] == 'a']['Port'][1]
。我模糊地记得在过去的调试中这个方法对我有效。 - PL200df[df['Host'] == 'a']['Port'][0]
或者print(df[df['Host'] == 'a']['Port'][0])
。 - Karn Kumar