从pandas datafram中提取一个字符串元素

2024-05-12 20:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,假设我有一个pandas数据帧x,我有兴趣从中提取一个值:

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

假设返回pandas.core.series.series类型的以下内容:

24    Boss
Name: ep_wb_ph_brand, dtype: object

但我想要的只是那串“老大”。用str()包装第一行代码也没有帮助,我只得到:

'24    Boss\nName: ep_wb_ph_brand, dtype: object'

我该如何提取字符串?


Tags: 数据pandasobjectfoobarvariablephloc
3条回答

获取数组最后一个值的代码(在Jupyter笔记本中运行,用>;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'

您可以使用string.split函数。

>>> s = '24    Boss\nName: ep_wb_ph_brand, dtype: object'
>>> s.split()[1]
'Boss'

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

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

如果将此值赋给变量,则只需访问第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]

您不需要将分配给变量来执行此操作,因此您只需编写x.loc[bar==foo]['variable_im_interested_in'][0](或其他选项的类似内容),但将越来越多的访问器和花哨的索引语法塞进单个表达式通常是一个坏主意。

还要注意,您可以在对loc的调用中直接索引感兴趣的列:

x.loc[bar==foo, 'variable_im_interested_in'][24]

相关问题 更多 >