我有一个df和几个以'comps'
开头的列,我想将它们的类型强制转换为float。
我试过
df = df.convert_dtypes() - Not Ok
df = df.columns.startswith('comps').astype(float) - Failed
有快速的方法吗?
感谢
获取以comps
开始并转换为浮点的所有列:
d = dict.fromkeys(df.columns[df.columns.str.startswith('comps')], 'float')
d = dict.fromkeys(df.filter(regex='^comps').columns, 'float')
df = df.astype(d)
print (df)
或者:
m = df.columns.str.startswith('comps')
df.loc[:, m] = df.loc[:, m].astype(float)
print (df)
或者:
c = df.filter(regex='^comps').columns
df[c] = df[c].astype(float)
print (df)
或者:
df.update(df.filter(regex='^comps').astype(float))
print (df)
如果铸造到浮动失败,有必要使用to_numeric
:
m = df.columns.str.startswith('comps')
df.loc[:, m] = df.loc[:, m].apply(pd.to_numeric, errors='coerce')
print (df)
或者:
c = df.filter(regex='^comps').columns
df[c] = df[c].apply(pd.to_numeric, errors='coerce')
print (df)
或者:
df.update(df.filter(regex='^comps').apply(pd.to_numeric, errors='coerce'))
print (df)