如何将熊猫中的数字字符串转换为整数

时间:2019-08-02 14:11:13

标签: python pandas type-conversion

我正在尝试寻找一种方法来将边界框坐标字符串转换为整数列表。我提出的每个想法都会引发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'

2 个答案:

答案 0 :(得分:0)

尝试:

df['bounding_box'].map(lambda x: x.split(', ')

或者也许:

df['bounding_box'].map(lambda x: x.replace(' ', '').split(','))

答案 1 :(得分:0)

我了解您拥有这样的数据框:

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

然后,如果要将“边界框”列转换为int,我将使用:

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

然后,如果打印(df),则会得到:

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