好的,所以说我有一个熊猫数据框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的熊猫系列:
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句