2 回答

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
filter以下是使用和select_dtypes查找列的一種方法:
cols = df.filter(like="col").select_dtypes("object").columns
或者,您可以提取 1 行并查找%:
cols = df.columns[df.loc[0].astype(str).str.endswith("%")]
兩者都會(huì)為您提供列名稱。
df[cols] = df[cols].replace("%", "", regex=True).astype(float)/100
print (df)
name date col1 col2 col3 col4
0 a 9/17 1.23 0.049 3.0 1.000
1 b 9/17 2.00 0.061 5.0 2.539
2 c 9/17 6.71 0.079 7.0 0.980

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
這可能會(huì)讓您開始:
import numpy as np
def percent_to_float(percent: str) -> float:
return float(percent[:-1])/100
df.select_dtype(object).apply(np.vectorize(percent_to_float))
這將獲取所有列dtype=object(字符串?dāng)?shù)據(jù)存儲(chǔ)在dtype=objectin 中),并應(yīng)用將百分比字符串(如 )轉(zhuǎn)換為浮點(diǎn)數(shù)(如 )的pandas函數(shù)。4.5%0.045
添加回答
舉報(bào)