0

I have a dataframe with CSVs in language column

     Name Language
0       A French,Espanol
1       B Deutsch,English

I wish to transform the above dataframe as below

    Name Language
0      A French
1      A Espanol
2      B Deutsch
3      B English

I tried the below code but couldn't accomplish

df=df.join(df.pop('Language').str.extractall(',$')[0] .reset_index(level=1,drop=True) .rename('Language')) .reset_index(drop=True)
8
  • Please post text/code, not images. And check out how-to-ask and How to create a Minimal, Reproducible Example. Commented Nov 22, 2019 at 10:15
  • Hope my question is clear now Commented Nov 22, 2019 at 10:26
  • did you try anything? what did not work? Commented Nov 22, 2019 at 10:27
  • Yes... I tried the below:- Commented Nov 22, 2019 at 10:29
  • 1
    always add code, data and error message in question, not in comment. It will be more readable and more people will see it. Commented Nov 22, 2019 at 10:34

2 Answers 2

1

pandas.DataFrame.explode should be suited for that task. Combine it with pandas.DataFrame.assign to get the desired column:

import pandas as pd

df = pd.DataFrame({'Name':['A', 'B'], 'Language': ['French,Espanol', 'Deutsch,English']})

df = df.assign(Language=df['Language'].str.split(',')).explode('Language')

#   Name Language
# 0    A   French
# 0    A  Espanol
# 1    B  Deutsch
# 1    B  English
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome Thanks a ton :)
1

First create a new dataframe with the same columns, then split second values and appent rows to the dataframe.

import pandas as pd

csv_df  = pd.DataFrame([['1', '2,3'], ['2', '4,5']], columns=['Name', 'Language'])
df = pd.DataFrame(columns=['Name ', 'Language'])

for index, row in csv_df .iterrows():
    name = row['Name']
    s = row['Language']
    txt = s.split(',')
    for x in txt:
        df = df.append(pd.Series([name, x], index=df.columns), ignore_index=True)

print(df)

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.