如何将Pandas Series类型从str转为list/numeric并去除引号获取列表值?
Got it, let's fix this issue where your df_small has columns with string representations of lists (like '[(181, 186)]') instead of actual list/numeric data. Here are two solid approaches to get this done:
1. Use ast.literal_eval (Most Reliable & Safe)
This is the go-to method because it safely parses valid Python literal values (like lists, tuples, numbers) from strings without the risks of using raw eval() (which can execute arbitrary code).
Step-by-Step Code:
import ast import pandas as pd # Example df_small (match your actual structure) df_small = pd.DataFrame({'center': ['[(181, 186)]', '[(200, 210)]', '[(150, 160)]']}) # Convert the string column to actual lists/tuples df_small['center'] = df_small['center'].apply(ast.literal_eval) # Optional: Extract numeric values into separate columns (if needed) df_small['center_x'] = df_small['center'].apply(lambda x: x[0][0]) # Get first value of the first tuple df_small['center_y'] = df_small['center'].apply(lambda x: x[0][1]) # Get second value of the first tuple
After running this, df_small['center'][0] will be the actual tuple (181, 186) instead of a string, and you can directly access its elements.
Handle Missing/Invalid Values:
If your column has empty strings or NaN, add a check to avoid errors:
df_small['center'] = df_small['center'].apply( lambda x: ast.literal_eval(x) if pd.notna(x) and x.strip() else [] # Replace invalid entries with empty list )
2. String Manipulation (For Fixed-Format Strings)
If your string format is exactly consistent (e.g., always wrapped in [] with tuples inside), you can use string splitting and stripping to convert values. This is faster for simple cases but less flexible if your string format varies.
Code Example:
# Strip outer brackets, split into tuple elements, convert to integers df_small['center'] = df_small['center'].str.strip('[]').apply( lambda x: tuple(map(int, x.strip('()').split(','))) )
This works for your example '[(181, 186)]': it strips the outer [], then strips the () from the remaining '181, 186', splits on commas, and converts each part to an integer.
内容的提问来源于stack exchange,提问作者hash_ir

