![](/img/trans.png)
[英]Convert all numeric values in dataframe to float but leave strings unchanged
[英]Replace in dataframe the '%' and then convert all the strings to float
我在 *.csv 中有這些標題的數據:
locationA_hhs locationA_hhs_ratio locationB_hhs locationB_hhs_ratio locationC_hhs locationC_hhs_ratio locationD_hhs locationD_hhs_ratio
這是該文件的一行內容:
16 0.52% 19 0.88% 14 0.46% 17 0.29%
我只需要讀入百分比作為浮動。 假設我已將 *.csv 讀入數據框,我試圖僅選擇以“ratio”結尾的列名,將“%”替換為“”,然后將所有這些列轉換為浮點型。 但是這段代碼不會產生那個結果。 請幫忙!
df_raw.select(lambda col: col.endswith('ratio'), axis=1).replace('%','').astype(float)
replace(X)
替換完整值X
,而不是值的一部分。 您必須使用regex=True
選項:
result = df_raw.loc[:, df.columns.str.endswith('_ratio')]\
.replace('%', '', regex=True).astype(float)
您可以使用雙百分號%%
來防止它被解釋,以便您可以打印實際的%
符號:
如下例:
test = "have it break."
selectiveEscape = "Print percent %% in sentence and not %s" % test
print selectiveEscape
Print percent % in sentence and not have it break.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.