从pandas数据帧中提取一个字符串元素

Hil*_*ers 7 python list names

好的,所以说我有一个pandas数据帧x,我有兴趣从中提取一个值:

> x.loc[bar==foo]['variable_im_interested_in']
Run Code Online (Sandbox Code Playgroud)

假设返回以下类型为pandas.core.series.Series:

24    Boss
Name: ep_wb_ph_brand, dtype: object
Run Code Online (Sandbox Code Playgroud)

但我想要的只是字符串'Boss'.包装第一行代码str()也无济于事,我得到:

'24    Boss\nName: ep_wb_ph_brand, dtype: object'
Run Code Online (Sandbox Code Playgroud)

我如何提取字符串?

ely*_*ely 5

根据您的评论,此代码返回一个长度为1的熊猫系列:

x.loc[bar==foo]['variable_im_interested_in']
Run Code Online (Sandbox Code Playgroud)

如果将此值分配给变量,则只需访问第0个元素即可获得所需的内容:

my_value_as_series = x.loc[bar==foo]['variable_im_interested_in']

# Assumes the index to get is number 0, but from your example, it might
# be 24 instead.
plain_value = my_value_as_series[0]

# Likewise, this needs the actual index value, not necessarily 0.
also_plain_value = my_value_as_series.ix[0]

# This one works with zero, since `values` is a new ndarray.
plain_value_too = my_value_as_series.values[0]
Run Code Online (Sandbox Code Playgroud)

你不具备分配给一个变量来做到这一点,所以你可以只写x.loc[bar==foo]['variable_im_interested_in'][0](或其他选项相似),但临时抱佛脚越来越多的访问和花哨的索引语法到一个单一的表达通常是一个坏主意。

另请注意,您可以在对的调用内直接将感兴趣的列编入索引loc

x.loc[bar==foo, 'variable_im_interested_in'][24]
Run Code Online (Sandbox Code Playgroud)

  • @HillarySanders 是的,前两个错误是预期的。对于您的情况,它打印出索引的数量是 24,因此您需要使用 24 而不是 0。当您使用 `.values` 时,您*不需要*需要这样做,因为是一个从 0 重新索引的新 ndarray。 (2认同)

dfr*_*kow 5

获取数组最后一个值的代码(在 Jupyter notebook 中运行,用 >s 标注):

> import pandas
> df = pandas.DataFrame(data=['a', 'b', 'c'], columns=['name'])
> df
    name
0   a
1   b
2   c
> df.tail(1)['name'].values[0]
'c'
Run Code Online (Sandbox Code Playgroud)