YIPYIP
YIPYIP

Reputation: 57

Split column with separator

| A             | B
| a;b;c         | 1;2;3
| a;b;c;d       | 1

In order to split the column , I am using

new = df["A"].str.split(";", n=5, expand=True).
df['A1'] = new[0]
df['A2'] = new[1]
df['A3'] = new[2]
df['A4'] = new[3]
df.drop(columns=["A"], inplace=True)

df['B1'] = new[0]
df['B2'] = new[1]
df['B3'] = new[2]
df.drop(columns=["B"], inplace=True)

Is there any other alternatives such that I do not need to count the number of data in each column?? I still need the output to be something like :

| A1| A2| A3| A4| B1| B2| B3
| a | b | c |   | 1 | 2 | 3
| a | b | c | d | 1 |   | 

Thanks!

Upvotes: 3

Views: 96

Answers (1)

ALollz
ALollz

Reputation: 59519

There's no need to specify the number of splits as it will by default split on every instance of the separator. The result will be be a DataFrame where the columns are a RangeIndex, so add the column as a prefix. Loop over each Series (as it's Series.str.split) and then concat to join the results.

df = pd.concat([df[col].str.split(';', expand=True).add_prefix(col) for col in df.columns],
               axis=1)

  A0 A1 A2    A3 B0    B1    B2
0  a  b  c  None  1     2     3
1  a  b  c     d  1  None  None

Just be careful, the 'B' columns contain strings '1' so if you want numbers used pd.to_numeric:

numerics = df.columns[df.columns.str.startswith('B')]
df[numerics] = df[numerics].apply(pd.to_numeric, errors='coerce')

  A0 A1 A2    A3  B0   B1   B2
0  a  b  c  None   1  2.0  3.0
1  a  b  c     d   1  NaN  NaN

Upvotes: 4

Related Questions