簡體   English   中英

在 pandas read_csv 中將百分比字符串轉換為浮點數

[英]Convert percent string to float in pandas read_csv

在 pandas 中使用 read_csv 時,有沒有辦法將像 '34%' 這樣的值直接轉換為 int 或 float? 我希望 '34%' 直接讀為 0.34

  1. read_csv中使用它不起作用:

    read_csv(..., dtype={'col':np.float})

  2. 將 csv 加載為“df”后,這也不適用於錯誤“float() 的無效文字:34%”

    df['col'] = df['col'].astype(float)

  3. 我最終使用了這個有效但冗長的方法:

    df['col'] = df['col'].apply(lambda x: np.nan if x in ['-'] else x[:-1]).astype(float)/100

您可以定義一個自定義函數來將百分比轉換為浮點數

In [149]:
# dummy data
temp1 = """index col 
113 34%
122 50%
123 32%
301 12%"""
# custom function taken from https://stackoverflow.com/questions/12432663/what-is-a-clean-way-to-convert-a-string-percent-to-a-float
def p2f(x):
    return float(x.strip('%'))/100
# pass to convertes param as a dict
df = pd.read_csv(io.StringIO(temp1), sep='\s+',index_col=[0], converters={'col':p2f})
df
Out[149]:
        col
index      
113    0.34
122    0.50
123    0.32
301    0.12
In [150]:
# check that dtypes really are floats
df.dtypes
Out[150]:
col    float64
dtype: object

我的百分比浮動代碼是由 ashwini 的回答提供的: 將字符串百分比轉換為浮點數的干凈方法是什么?

你非常接近你的df嘗試。 嘗試改變:

df['col'] = df['col'].astype(float)

至:

df['col'] = df['col'].str.rstrip('%').astype('float') / 100.0
#                     ^ use str funcs to elim '%'     ^ divide by 100
# could also be:     .str[:-1].astype(...

Pandas 支持 Python 的字符串處理能力。 只需在您想要的字符串函數之前加上.str ,看看它是否滿足您的需求。 (當然,這也包括字符串切片。)

上面我們使用.str.rstrip()去除尾隨百分號,然后我們將整個數組除以 100.0 以將百分比轉換為實際值。 例如,45% 相當於 0.45。

雖然.str.rstrip('%')也可以只是.str[:-1] ,但我更喜歡明確刪除 '%' 而不是盲目地刪除最后一個字符,以防萬一......

問:如何從百分比中獲取熊貓數據框/系列?

dfp = df[col].str.rstrip('%').astype(float) / 100

說明轉換為字符串,如果 % 則去掉最后一個字符。 轉換為浮點數並除以 100。

@Gary02127 的變體

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM