将数据框列的列表拆分为两个数据框列 [英] Split a dataframe column's list into two dataframe columns

查看:123
本文介绍了将数据框列的列表拆分为两个数据框列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在有效地尝试从MS Excel执行文本到列操作,但是在Pandas中进行.

I'm effectively trying to do a text-to-columns (from MS Excel) action, but in Pandas.

我有一个数据框,其中包含诸如1_1、2_1、3_1之类的值,我只想将这些值放在下划线的右边.我想出了如何分割字符串,这为我提供了分解后的字符串的列表,但我不知道如何将其分解为不同的数据框列.

I have a dataframe that contains values like: 1_1, 2_1, 3_1, and I only want to take the values to the right of the underscore. I figured out how to split the string, which gives me a list of the broken up string, but I don't know how to break that out into different dataframe columns.

这是我的代码:

import pandas as pd

test = pd.DataFrame(['1_1','2_1','3_1'])
test.columns = ['values']

test = test['values'].str.split('_')

我得到类似:[1,1],[2,1],[3,1].

I get something like: [1, 1], [2, 1], [3, 1].

我想要得到的是两个单独的列:

What I'm trying to get is two separate columns:

col1:1、2、3 col2:1、1、1

col1: 1, 2, 3 col2: 1, 1 ,1

有什么想法吗?预先感谢您的帮助

Thoughts? Thanks in advance for your help

推荐答案

在执行split来获取多列时使用expand=True:

Use expand=True when doing the split to get multiple columns:

test['values'].str.split('_', expand=True)

如果只有一个下划线,并且您只关心右边的值,则可以使用:

If there's only one underscore, and you only care about the value to the right, you could use:

test['values'].str.split('_').str[1]

这篇关于将数据框列的列表拆分为两个数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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