Reputation: 59
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
Upvotes: 1
Views: 284
Reputation: 8302
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
Upvotes: 1
Reputation: 5603
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)]
Upvotes: 1
Reputation: 5746
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)]
Upvotes: 2