简体   繁体   中英

CSV File-Pandas dataFrame column separation

I have this data set as such, 在此处输入图片说明

As you can see that 3rd column (Age at , start of presidency ) have been merged as well as 4th column(Age at, end of presidency) How can I separate them ? Thanks in advance.

If possible split by uppercase:

data = [{'Age atend of presidency': '65 years, 10 daysMar 4, 1797'}, 
        {'Age atend of presidency': '65 years, 10 daysMar 4, 1797'}
         ,{'Age atend of presidency': '65 years, 10 daysMar 4, 1797'}]

df = pd.DataFrame(data)

df[['age1','end2']] = df['Age atend of presidency'].str.split("([A-Z][^A-Z]*)", expand=True).iloc[:, :-1]
print (df)
            Age atend of presidency               age1         end2
0  65 years, 10 daysMar 4, 1797  65 years, 10 days  Mar 4, 1797
1  65 years, 10 daysMar 4, 1797  65 years, 10 days  Mar 4, 1797
2  65 years, 10 daysMar 4, 1797  65 years, 10 days  Mar 4, 1797

Or you can split by days :

df[['age1','end2']] = df['Age atend of presidency'].str.split("days", expand=True)
df['age1'] += 'days'
print (df)
        Age atend of presidency               age1         end2
0  65 years, 10 daysMar 4, 1797  65 years, 10 days  Mar 4, 1797
1  65 years, 10 daysMar 4, 1797  65 years, 10 days  Mar 4, 1797
2  65 years, 10 daysMar 4, 1797  65 years, 10 days  Mar 4, 1797

Or:

df[['age1','a', 'end2']] = df['Age atend of presidency'].str.split("(days)", expand=True)
df['age1'] += df.pop('a')

If it is STR you can use X.split(','). For example:

 df['Age atend of presidency'].apply(lambda x: x.split(','))

if it is not a STR

df['Age atend of presidency'].apply(lambda x: str(x).split(','))

or

df['Age'] = df['Age atend of presidency'].apply(lambda x: x.split(',')[0])
df['days'] = df['Age atend of presidency'].apply(lambda x: x.split(',')[1])
df['date'] = df['Age atend of presidency'].apply(lambda x: x.split(',')[2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM