我正在尝试将列从字符串转换为 float 。 df 列如下所示。有些行中没有数字,而是一个空格 ' '。
col
'1.1, 1.0006'
' '
我试图将每个数字四舍五入到小数点后第三位。输出看起来像这样。
col
'1.100, 1.001'
' '
我的想法:
df['col'] = df['col'].astype(float)
df['col'] = df['col'].round(3)
最佳答案
我认为你需要:
df = pd.DataFrame({'col':["'1.1, 1.0006'", "' '"]})
print (df)
def func(x):
out = []
#split and strip values, try convert each value to float, if error, get original value
for y in x.strip("'").split(', '):
try:
out.append(round(float(y), 3))
except:
out.append(y)
return (out)
df['new'] = df['col'].apply(func)
print (df)
col new
0 '1.1, 1.0006' [1.1, 1.001]
1 ' ' [ ]
如果需要来自 float 的字符串,请使用 f-strings
:
def func(x):
out = []
for y in x.strip("'").split(', '):
try:
out.append(f'{round(float(y), 3):.3f}')
except:
out.append(y)
return (out)
df['new'] = df['col'].apply(func)
print (df)
col new
0 '1.1, 1.0006' [1.100, 1.001]
1 ' ' [ ]
对于字符串,添加 join
到结尾:
def func(x):
out = []
for y in x.strip("'").split(', '):
try:
out.append(f'{round(float(y), 3):.3f}')
except:
out.append(y)
return (', '.join(out))
df['new'] = df['col'].apply(func)
print (df)
col new
0 '1.1, 1.0006' 1.100, 1.001
1 ' '
关于python - 将 float 字符串转换为圆角 float 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55163787/