获取最后一个“列"在对 Pandas DataFrame 中的列进行 .str.split() 操作之后 [英] Get last "column" after .str.split() operation on column in pandas DataFrame

查看:24
本文介绍了获取最后一个“列"在对 Pandas DataFrame 中的列进行 .str.split() 操作之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Pandas DataFrame 中有一个列,我想将其拆分为一个空间.使用 DataFrame.str.split(' ') 进行拆分非常简单,但我无法从最后一个条目创建新列.当我 .str.split() 列时,我得到一个数组列表,但我不知道如何操作它来为我的 DataFrame 获取一个新列.

这是一个例子.该列中的每个条目都包含符号数据价格",我想拆分价格(并最终在一半情况下删除p"...或c").

将pandas导入为pdtemp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})temp2 = temp.ticker.str.split(' ')

产生的结果

0 ['spx', '5/25/2001', 'p500']1 ['spx', '5/25/2001', 'p600']2 ['spx', '5/25/2001', 'p700']

但是 temp2[0] 只给出一个列表条目的数组,temp2[:][-1] 失败.如何将每个数组中的最后一个条目转换为新列?谢谢!

解决方案

这样做:

在[43]中:temp2.​​str[-1]出[43]:0 p5001 p6002 p700名称:行情

所以总的来说就是:

<预><代码>>>>temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})>>>temp['ticker'].str.split(' ').str[-1]0 p5001 p6002 p700名称:股票代码,数据类型:对象

I have a column in a pandas DataFrame that I would like to split on a single space. The splitting is simple enough with DataFrame.str.split(' '), but I can't make a new column from the last entry. When I .str.split() the column I get a list of arrays and I don't know how to manipulate this to get a new column for my DataFrame.

Here is an example. Each entry in the column contains 'symbol data price' and I would like to split off the price (and eventually remove the "p"... or "c" in half the cases).

import pandas as pd
temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
temp2 = temp.ticker.str.split(' ')

which yields

0    ['spx', '5/25/2001', 'p500']
1    ['spx', '5/25/2001', 'p600']
2    ['spx', '5/25/2001', 'p700']

But temp2[0] just gives one list entry's array and temp2[:][-1] fails. How can I convert the last entry in each array to a new column? Thanks!

解决方案

Do this:

In [43]: temp2.str[-1]
Out[43]: 
0    p500
1    p600
2    p700
Name: ticker

So all together it would be:

>>> temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
>>> temp['ticker'].str.split(' ').str[-1]
0    p500
1    p600
2    p700
Name: ticker, dtype: object

这篇关于获取最后一个“列"在对 Pandas DataFrame 中的列进行 .str.split() 操作之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆