0

I want to split a column from Python data frame to two separate columns, but for them to stay under it's name.

Example:

enter image description here

to

enter image description here

dummydummy
  • 91
  • 1
  • 6
  • Hi and welcome on SO. It will be great if you can have a look at [ask] and then try to produce a [mcve]. – rpanai Jul 06 '23 at 14:47
  • Your question needs a minimal reproducible example consisting of sample input, expected output, actual output, and only the relevant code necessary to reproduce the problem. See [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) for best practices related to Pandas questions. – itprorh66 Jul 06 '23 at 14:47

1 Answers1

0

I use a small custom function (I found it here on SO somewhere...) to do this.

def prepend_index_level(index, key, name=None):
    names = index.names
    if index.nlevels==1:
        # Sequence of tuples
        index = ((item,) for item in index)
    tuples_gen = ((key,)+item for item in index)
    return pd.MultiIndex.from_tuples(tuples_gen, names=[name]+names)


names = [i.split()[0] for i in df.name.values]
surnames = [i.split()[-1] for i in df.name.values]
df2 = pd.DataFrame({'First':names, 'Surname':surnames})
   
df2.columns = prepend_index_level(df2.columns, key='Name', name="")

print(df2)

   Name        
  First Surname
0  Asdf    Gsdf
1  Basd     Foo
alec_djinn
  • 10,104
  • 8
  • 46
  • 71