好吧,假设我有一个 pandas 数据框 x,我有兴趣从中提取一个值:
> x.loc[bar==foo]['variable_im_interested_in']
假设返回以下类型的 pandas.core.series.Series:
24 Boss
Name: ep_wb_ph_brand, dtype: object
但我想要的只是字符串“Boss”。将第一行代码包装在 str()
中也无济于事,我只是得到:
'24 Boss\nName: ep_wb_ph_brand, dtype: object'
如何提取字符串?
最佳答案
根据您的评论,此代码返回长度为 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]
关于python - 从 Pandas 数据框中仅提取一个字符串元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732745/