这是我的数据集的示例。
d = {'numbers': [['1.9x1.4x2.0','1.5x1.1x1.3','11','8x10','3.7x3.8'],['1.0x1.5', '1.7x0.7', '1.4', '0.8', '3.4x4.2x4.5', '1.0x1.5']]}
df2 = pd.DataFrame(data=d)
我想从每个用逗号分隔的元素中提取第一个数字,并将其转换为浮点数。所以我的预期输出是
df2['output]=[[1.9,1.5,11,8,3.7],[1.0,1.7,1.4,0.8,3.4,1.0]]
我不确定当x存在时如何获取第一个元素,str [0]将不起作用,否则我能想到的是
df2.numbers.apply(lambda x: x.split(',') ).apply(lambda x: [float(i) for i in x])
但是,如果x不存在,这将起作用。请帮忙!
使用 apply
例如:
d = {'numbers': [['1.9x1.4x2.0','1.5x1.1x1.3','11','8x10','3.7x3.8'],['1.0x1.5', '1.7x0.7', '1.4', '0.8', '3.4x4.2x4.5', '1.0x1.5']]}
df2 = pd.DataFrame(data=d)
df2['output']= df2["numbers"].apply(lambda x: [i.split("x")[0] for i in x])
print(df2)
输出:
numbers output
0 [1.9x1.4x2.0, 1.5x1.1x1.3, 11, 8x10, 3.7x3.8] [1.9, 1.5, 11, 8, 3.7]
1 [1.0x1.5, 1.7x0.7, 1.4, 0.8, 3.4x4.2x4.5, 1.0x... [1.0, 1.7, 1.4, 0.8, 3.4, 1.0]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句