Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 仅从数据帧中提取字符串元素_Python_List_Names - Fatal编程技术网

Python 仅从数据帧中提取字符串元素

Python 仅从数据帧中提取字符串元素,python,list,names,Python,List,Names,好的,假设我有一个熊猫数据帧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: obje

好的,假设我有一个熊猫数据帧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'

如何提取字符串?

您可以使用
string.split
函数

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

根据您的评论,此代码将返回长度为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\u im\u interest\u in'][0]
(或其他选项类似),但将越来越多的访问器和奇特的索引语法塞进一个表达式通常是一个坏主意

还请注意,您可以直接在调用
loc
的内部索引感兴趣的列:

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

获取数组最后一个值的代码(在Jupyter笔记本中运行,用>s表示):


是 啊这是我最后的选择;这似乎不雅。但是你是对的。你能添加
类型的输出(x.loc[bar==foo]['variable\u im\u interest\u in'])
。。。我不清楚归还的是什么。如果
'Boss'
是存储在相关单元格中的预期值,那么没有理由认为其他索引号、名称和数据类型内容应该是该值的一部分。是的@F先生,它是pandas.core.series.SeriesAh,它是长度为1的系列。所以只需访问第0个条目!试试这个:
x.loc[bar==foo]['variable\u im\u interest\u'][0]
.Hm,这完全是有道理的,尽管在末尾添加[0]会引发pandas键错误,而在末尾添加[:1]会返回相同的pandas序列,而不是字符串。。。(如果您的名字引用的是开发受阻,请再说+1000。)@thelatemail谢谢,修正了感谢F先生。前两个抛出错误([0]和.ix[0]),但第三个策略有效(.value[0])。@hillarysands是的,前两个错误是预期的。对于您的情况,打印出来的索引数是24,因此您需要使用24而不是0。在使用
.values
的情况下,您不需要这样做,因为这是一个从0重新索引的新数据数组。这是一个漂亮的pythonic!为什么该语法与“df['name'].tail(1.values[0]”相同?
> 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'