import pandas as pd
df = pd.DataFrame([["one", 1.2, "", "4,3"],
["two","1,7", "2,4", 0.55],
["three","", 5.4, "3,9"]],
columns=['a','b','c','d'])
如何将列b到d中的逗号替换为点并使这些列成为数字? 列a(或任意数量的前导列)应保持不变(也可包含逗号)
答案 0 :(得分:3)
import re
for col in ['b', 'c', 'd']:
df[col] = pd.to_numeric(df[col].apply(lambda x: re.sub(',', '.', str(x))))
答案 1 :(得分:0)
你可以试试这个:
JpaSort.unsafe("d")
输出:
df = df.set_index('a')
df.apply(lambda x: x.str.replace(',','.')).combine_first(df).apply(lambda x:pd.to_numeric(x,errors='coerce')).reset_index()
a b c d
0 one 1.2 NaN 4.30
1 two 1.7 2.4 0.55
2 three NaN 5.4 3.90