如何在Pandas中将DataFrame列表列的元素转换为字符串类型
Hey there! Let's break down the issue with your current code and fix it to get exactly the result you want.
Why Your Current Code Isn't Working
The line df3['label'] = [str(i) for x in df3['label'] for i in x] is flattening all elements from your label lists into a single 1D list instead of preserving each row's list structure. For example, with your sample data, this would create a long list like ['0','0','1','1','0','0','1','1','316.0',...]—which has way more elements than your 266-row DataFrame. This mismatch is why it fails to produce the output you need.
Simple Fixes to Preserve List Structure
You have two straightforward, effective ways to convert each element in the label lists to strings while keeping the per-row list intact:
Option 1: Use pandas.Series.apply() with a Lambda
This is a clean, pandas-native approach:
df3['label'] = df3['label'].apply(lambda x: [str(i) for i in x])
The apply() method runs the lambda function on every list in the label column. The lambda takes each list x, converts every element i to a string, and returns the modified list for that row.
Option 2: Nested List Comprehension
If you prefer list comprehensions, adjust the structure to keep each row's list intact:
df3['label'] = [[str(i) for i in x] for x in df3['label']]
Here, the outer comprehension loops through each list in df3['label'], and the inner comprehension converts each element in that sublist to a string—creating a new, string-filled list for every row.
Test with Your Sample Data
Let's confirm this works with your example:
import pandas as pd # Sample data matching your structure data = { 'Id': ['4cfab', '924cf', '916b8', '0f549', 'db696'], 'label': [[0,0,1,1], [0,0,1,1], [316.0,318.0], [0,0,1,1], [345.0,39.0,9]] } df3 = pd.DataFrame(data) # Apply the fix (either option works!) df3['label'] = df3['label'].apply(lambda x: [str(i) for i in x]) print(df3)
This outputs exactly the result you're targeting:
Id label 0 4cfab ['0', '0', '1', '1'] 1 924cf ['0', '0', '1', '1'] 2 916b8 ['316.0', '318.0'] 3 0f549 ['0', '0', '1', '1'] 4 db696 ['345.0', '39.0', '9']
内容的提问来源于stack exchange,提问作者pasan

