0

For example I have two rows:

ID,dep_id
EMP1,1,2,3
EMP2,4,5,6

I want the output as :

ID,dep_id
EMP1,1
EMP1,2
EMP1,3
EMP2,4
EMP2,5
EMP2,6
0

1 Answer 1

1

You can use pandas for this:

import pandas as pd
import io

data = '''ID,dep_id
EMP1,"1,2,3"
EMP2,"4,5,6"'''

df = pd.read_csv(io.StringIO(data)) # insert your csv here
df['dep_id'] = ('['+df['dep_id']+ ']').apply(pd.eval) # turn string to list
df.explode('dep_id')df.explode('dep_id').reset_index(drop=True)

Output:

ID dep_id
0 EMP1 1
1 EMP1 2
2 EMP1 3
3 EMP2 4
4 EMP2 5
5 EMP2 6
Sign up to request clarification or add additional context in comments.

5 Comments

data = '''ID,dep_id EMP1,"1,2,3" EMP2,"4,5,6"''' The data is already stored in a df Hence this is not working df = pd.read_csv(io.StringIO(data)) # insert your csv here
then .... skip that line?
Getting error : TypeError: can only concatenate str (not "int") to str
what if we take the table like : ID,dep_id EMP1,1,2,3 EMP2,4,5,6
I can't guess the dtype of your columns. Was assuming it was a string. If it is a list of ints you can just do df.explode('dep_id')df.explode('dep_id')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.