Home > database >  How to split one column with mixed values of integers and strings into two different columns using p
How to split one column with mixed values of integers and strings into two different columns using p

Time:05-19

HEADER A header B
test A
test1 B
test2 1
test3 E
test4 2

INTO

HEADER A header c header d
test A Nan
test1 B Nan
test2 Nan 1
test3 E Nan
test4 Nan 2

In short i want to split header B INTO header c and header d as shown in the table. Using pandas

CodePudding user response:

You can use pandas.Series.str.isnumeric then with Series.mask

df['header c'] = df['header B'].mask(df['header B'].str.isnumeric(), np.nan)
df['header d'] = df['header B'].where(df['header B'].str.isnumeric(), np.nan)
print(df)

  HEADER A header B header c header d
0     test        A        A      NaN
1    test1        B        B      NaN
2    test2        1      NaN        1
3    test3        E        E      NaN
4    test4        2      NaN        2

CodePudding user response:

If you have strings, use str.extract:

df[['header c', 'header b']] = df['header B'].str.extract(r'^(\D )|(\d )$')

output:

  HEADER A  header B header c header b
0     test         A        A      NaN
1    test1         B        B      NaN
2    test2         1      NaN        1
3    test3         E        E      NaN
4    test4         2      NaN        2
  • Related