首页 > 解决方案 > 如何将熊猫中的一串数字转换为整数

问题描述

我正在尝试找到一种将边界框坐标字符串转换为整数列表的方法。我的每个想法都会引发 KeyError,有什么提示吗?

for row in bounding_image_df['bounding_box']:
    bounding_image_df['bounding_box'][row] = list(map(int, bounding_image_df['bounding_box'][row].split(' ')))
for row in bounding_image_df['bounding_box']:
    bounding_image_df['bounding_box'][row] = bounding_image_df['bounding_box'][row].split(' ')
for row in bounding_image_df['bounding_box']:
    pd.to_numeric(bounding_image_df['bounding_box'][row], errors='ignore')

这些都抛出相同的错误,一个关键错误,唯一的描述是数据帧第一行中未转换的字符串。

KeyError: '60 127 253 72'

标签: pythonpandastype-conversion

解决方案


I've understood you have a dataframe like this:

dicc = {'colum1': ['row1', 'row2', 'row3'],
        'bounding_box': ['60 127 253 72','55 137 243 22','56 227 113 78']
       }
df = pd.DataFrame(dicc)
df

Then, if you want to convert the column 'bounding box' to int, I would use:

df['bounding_box']=df['bounding_box'].str.split(' ').apply(lambda x: [int(num) for num in x])

Then if you print(df), you'll get:

colum1  bounding_box
0   row1    [60, 127, 253, 72]
1   row2    [55, 137, 243, 22]
2   row3    [56, 227, 113, 78]

推荐阅读