从另一列的子字符串创建列 [英] Create column from a substring of another column

查看:36
本文介绍了从另一列的子字符串创建列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas数据框对象。我想从现有列的子字符串创建新列。我的数据如下:

I have a Pandas dataframe object. I want to create new columns from substrings of an existing column. My data looks like this:

    Date        variable                 want1          want2   want3
0   02-01-08    Australia - Sydney - A   Australia      Sydney  A
1   03-01-08    Australia - Sydney - A   Australia      Sydney  A
2   04-01-08    Australia - Sydney - A   Australia      Sydney  A
3   05-01-08    Canada - Toronto - B     Canada         Toronto B
4   06-01-08    Canada - Toronto - B     Canada         Toronto B

其中 want1 want3 是我所需要的。

推荐答案

您可以为此使用 pd.Series.str.split

df[['want1', 'want2', 'want3']] = df['variable'].str.split(' - ', expand=True)

这篇关于从另一列的子字符串创建列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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