Home > Mobile >  How to cut data from one column and paste into a new column in Python -> Pandas?
How to cut data from one column and paste into a new column in Python -> Pandas?

Time:11-08

For example, I have the DataFrame:

import pandas as pd

a = [{'name': 'RealMadrid_RT'}, {'name': 'Bavaria_FD'}, {'name': 'Lion_NS'}]
df = pd.DataFrame(a)

I need to create new column -> df['name_2'], next, cut the data from column df['name'] and paste to column df['name_2']. I require getting the next result how on the screenshot

enter image description here

I will be grateful for the answer

CodePudding user response:

This will work, assuming you don't want the underscore in the second column:

df = df['name'].str.partition('_').drop(1, axis=1)
df.columns = ['name', 'name2']

CodePudding user response:

Use str.extract to get the expected outcome:

# With underscore
>>> df['name'].str.extract('(.*)(_.*)').rename(columns={0: 'name', 1: 'name_2'})
         name name_2
0  RealMadrid    _RT
1     Bavaria    _FD
2        Lion    _NS

# Without underscore
>>> df['name'].str.extract('(.*)_(.*)').rename(columns={0: 'name', 1: 'name_2'})
         name name_2
0  RealMadrid     RT
1     Bavaria     FD
2        Lion     NS
  • Related