Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split 'number' to separate columns in pandas DataFrame

I have a dataframe;

df=pd.DataFrame({'col1':[100000,100001,100002,100003,100004]})

     col1    
0   100000    
1   100001
2   100002
3   100003
4   100004

I wish I could get the result below;

    col1   col2    col3
0   10     00       00 
1   10     00       01
2   10     00       02
3   10     00       03
4   10     00       04

each rows show the splitted number. I guess the number should be converted to string, but I have no idea next step.... I wanna ask how to split number to separate columns.

like image 277
Heisenberg Avatar asked Aug 30 '16 01:08

Heisenberg


People also ask

How do you split a column of numbers in Python?

split() Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string.

How do I split a single column into multiple columns in Python?

We can use str. split() to split one column to multiple columns by specifying expand=True option. We can use str. extract() to exract multiple columns using regex expression in which multiple capturing groups are defined.

How do you split values in a data frame?

We can use the pandas Series. str. split() function to break up strings in multiple columns around a given separator or delimiter. It's similar to the Python string split() method but applies to the entire Dataframe column.


1 Answers

# make string version of original column, call it 'col'
df['col'] = df['col1'].astype(str)

# make the new columns using string indexing
df['col1'] = df['col'].str[0:2]
df['col2'] = df['col'].str[2:4]
df['col3'] = df['col'].str[4:6]

# get rid of the extra variable (if you want)
df.drop('col', axis=1, inplace=True)
like image 160
benten Avatar answered Nov 08 '22 18:11

benten