Python suggestion is required. I need to divide an Excel sheet with 20 columns into two pre and post-columns, where pre will have a value of 12 and post will have a value of 23, and so on. These columns should also be placed immediately under their respective parent columns using pandas.

Input:

```| Column A |
| -------- |
| 12 --> 23|
| 13 --> 24|
```

Output

```| column A |
|pre| |post|
| 12| | 23 |
| 13| | 24 |
```

I can't use the column name directly because there are many columns.

I tested the subsequent code If I knew the column name, it worked, but if I had to loop the columns without knowing their names, it didn't.

```df = pd.read_excel('path/to/excel_file.xlsx')

for col in df.columns:
new_cols = df[col].str.split(expand=True)

df[col + '_1'] = new_cols
df[col + '_2'] = new_cols
df.drop(columns=df.columns[:-2], inplace=True)
```

It's not working for me

Apr 7 in Others 173 views

## 1 answer to this question.

Use str.split:

```df[['pre', 'post']] = df['Column A'].str.split(r'\s*-->\s*', expand=True)
print(df)

# Output
Column A pre post
0  12 --> 23  12   23
1  13 --> 24  13   24
```

So for multiple columns:

```data = []

for col in df.columns:
new_cols = df[col].str.split(r'\s*-->\s*', expand=True)
if new_cols.shape == 2:
df = df.drop(columns=col)
df = pd.concat([df, *data], axis=1)
```

Output:

```>>> df
Column A_0 Column A_1
0         12         23
1         13         24```
• 38,010 points

## How to paste an Excel chart into PowerPoint placeholder using Python?

Very near indeed! Copy and Paste are ...READ MORE

## How to change two different date format into single date format in excel

With data in A2, in B2 enter: =IF(ISNUMBER(A2),A2,DATE(LEFT(A2,4),MID(A2,6,2),RIGHT(A2,2))) and apply your format ...READ MORE

+1 vote

## View onto a numpy array?

just index it as you normally would. ...READ MORE

## Dimension in python numpy

Use the .shape to print the dimensions ...READ MORE

## How to slice an array using python numpy? Is there any numpy tutorial which has covered all its operations?

Slicing is basically extracting particular set of ...READ MORE