1

This is how my data looks,

emp_id  col1  col2  col3
1234,abc|de,2020|2011,89
5639,ma,2010|2019,90

This is how data need to be changed and saved into the file

 emp_id  col1  col2  col3
 1234    abc   2020  89
 1234    abc   2011  89
 1234    de    2020  89
 1234    de    2011  89
 5639    ma    2010  90
 5639    ma    2019  90

Is there an easy way to do this in python?

7

1 Answer 1

0

I don't think I have the easiest way but the following code works on your example:

import pandas as pd
# read your example
df = pd.read_csv(
    io.StringIO(
        r"""emp_id,col1,col2,col3
1234,abc|de,2020|2011,89
5639,ma,2010|2019,90"""
    )
)

# split and expand the column with pipe sign
# expanded_col1 and expanded_col2 are dataframes
# rename the column in order to find them after
expanded_col1 = df.col1.str.split('|', expand=True).rename(
    lambda x: f'col1_{x}', axis='columns'
)
expanded_col2 = df.col2.str.split('|', expand=True).rename(
    lambda x: f'col2_{x}', axis='columns'
)

# create all combinations from values of string split
to_concat = []
for col1, col2 in itertools.product(expanded_col1, expanded_col2):
    to_concat.append(
        pd.concat(
            [
                # put back the initial column name
                expanded_col1.loc[:, [col1]].rename(
                    lambda x: x.split('_')[0], axis='columns'
                ),
                expanded_col2.loc[:, [col2]].rename(
                    lambda x: x.split('_')[0], axis='columns'
                ),
            ],
            axis='columns',
        ).dropna()
    )


result = pd.merge(  # merge combinations and other columns
    df.drop(['col1', 'col2'], axis='columns'),  # drop initial split columns
    pd.concat(to_concat), # concat all combinations
    left_index=True,
    right_index=True,
)

Result:

   emp_id  col3 col1  col2
0    1234    89  abc  2020
0    1234    89  abc  2011
0    1234    89   de  2020
0    1234    89   de  2011
1    5639    90   ma  2010
1    5639    90   ma  2019
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.