I have dataframe (df3
) with 266 rows which looks like below. The label columns list items are of type int.
Id | label |
---|---|
4cfab | [0,0,1,1] |
924cf | [0,0,1,1] |
916b8 | [316.0,318.0] |
0f549 | [0,0,1,1] |
db696 | [345.0,39.0,9] |
I want the result like below:
Id | label |
---|---|
4cfab | ['0', '0', '1','1'] |
924cf | ['0', '0', '1','1'] |
916b8 | ['316.0','318.0'] |
0f549 | ['0', '0', '1','1'] |
db696 | ['45.0','39.0','9'] |
I've tried the following but it didn't work:
df3['label'] = [str(i) for x in df3['label'] for i in x]
CodePudding user response:
You can use the pandas.Series.map
method to broadcast a function over each element of the series. In this case, each element is a list. So for each list, we want to map
the function str
over each element of the list.
df3['label'] = df3.label.map(lambda x: list(map(str, x)))
CodePudding user response:
You can try as a list comprehension within a map()
:
df3['label'] = df3['label'].map(lambda x: [str(y) for y in x])
CodePudding user response:
You can try using apply()
to add the quotation marks. The for loop in the lambda function loops through all the values within the lists in the df3['label']
column.
df3['label'] = df3['label'].apply(lambda x: ["'" str(i) "'" for i in range(len(x))])