1

I have a dataframe df with a column called columnList as str.

"1 2,7 8,10 7" 

Then I converted them to a list as shown :

[1 2,7 8,10 7] 

I want to convert the value inside list to tuple :

[(1,2),(7,8),(10,7)] 

Current code :

temp = df['columnList'].str.split(',') result = list(zip(temp[::2], temp[1::2])) print(result) 

I'm getting empty list.

df looks like this :

column1 columnList YY 1 2,7 8,10 7 

Name: df, dtype: object

3 Answers 3

2

You don't need to use zip here, just iterate over the list, split each element and store it as a tuple.

l = [ '1 2', '7 8', '10 7'] [tuple(int(i) for i in numbers.split()) for numbers in l] #[(1, 2), (7, 8), (10, 7)] 
Sign up to request clarification or add additional context in comments.

Comments

1

try this,

df.columnsList.apply(lambda x : [tuple(map(int, x.split())) for x in "1 2, 7 8, 10 7".split(",")]) 

output,

0 [(1, 2), (7, 8), (10, 7)] Name: columnsList, dtype: object 

2 Comments

It works but the numbers are not converted to float. It is in string
This works too : apply(lambda x : [tuple(map(float,x.split())) for x in x.split(",")]) Thank you!
1

You could map the characters to ints after splitting them, then convert the map object to a tuple:

temp = df['columnList'].str.split(',') result = [tuple(map(int, num.split())) for num in temp] print(result) # [(1, 2), (7, 8), (10, 7)] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.