Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

python - Split a dataframe column's list into two dataframe columns

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

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.

Here is my code:

import pandas as pd

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

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

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

Thoughts? Thanks in advance for your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...