I want to split a column from Python data frame to two separate columns, but for them to stay under it's name.
Example:
to
I want to split a column from Python data frame to two separate columns, but for them to stay under it's name.
Example:
to
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