1

Ho everyone,

I want to create a dataframe from list, where each element from a list is a column. Example:

    Col
0   A_1
1   A_2
2   A_1
3   B_3
4   B_2

I want to have a dataframe like this

Col1 . col2 
0   A .  1  
1   A .  2
2   B .  3
3   B .  2

....

split by the '_' and make two columns and remove the duplicate

Thanks in advance

2 Answers 2

3

Use:

df[['Col1','Col2']]=df.pop('Col').str.split("_",expand=True)
df = df.drop_duplicates()
print(df)

  Col1 Col2
0    A    1
1    A    2
3    B    3
4    B    2
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer, I had this error ValueError: Columns must be same length as key
@noaai possible that you have 2 underscores in some data?
1

Using extract

yourdf=df.drop_duplicates().Col.str.extract(r'(?P<col1>[AB])_(?P<col2>\d)')
yourdf
Out[16]: 
  col1 col2
0    A    1
1    A    2
3    B    3
4    B    2

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.