Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split columns and name them using pandas

Tags:

python

pandas

I want to split a column into 3 based on a delimiter ":" and I am able to do that using the code below. But now want to change the names of the split columns from the default of 1,2,3,4. Please advice how I can do that.

from pandas import *
df = DataFrame(
     {'CustomerName' : ["Paul", "John"], 'Seatblocks' : ["2:218:10:4,6","2:218:10:4,6"]}); 
df

df.join(df.Seatblocks.apply(lambda x: Series(x.split(':'))))
like image 712
Al Merchant Avatar asked Oct 15 '25 18:10

Al Merchant


1 Answers

Just rename them:

df.rename(columns={0:'col_1', 1:'col_2', 2:'col_3', 3:'col_4'},inplace=True)

A more obscure method is to form a union of the new names to the first 2 elements of your columns and assign directly:

In [14]:

df.columns = df.columns[:2] | pd.Index(['col_1', 'col_2', 'col_3', 'col_4'])
df
Out[14]:
  CustomerName    Seatblocks col_1 col_2 col_3 col_4
0         Paul  2:218:10:4,6     2   218    10   4,6
1         John  2:218:10:4,6     2   218    10   4,6
like image 169
EdChum Avatar answered Oct 18 '25 08:10

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!