gpt4 book ai didi

python - 如何从 python 中存储在数据框中的模式的字符串中提取第一个数字?

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:18 24 4
gpt4 key购买 nike

这是我的数据集的示例。

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)

我想从逗号分隔的每个元素中提取第一个数字并将其转换为 float 。所以我的预期输出是

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 不存在,这将起作用。请帮忙!

最佳答案

使用应用

例如:

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]

关于python - 如何从 python 中存储在数据框中的模式的字符串中提取第一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com