2013-05-20 11 views
12

私はpandasが新しく、文字列としてフォーマットされた複数の列をfloat64に変換する方法を理解しようとしています。現在、私は以下のことを行っていますが、apply()やapplymap()のように、この作業をさらに効率的に行うことができるはずです...残念ながら、私は新人の方が多すぎます。現在pandasはデータフレーム内の複数の列に対して文字列を浮動小数点に変換します

for column in ['field1', 'field2', 'field3']: 
    data[column] = data[column].str.rstrip('%').astype('float64')/100 

答えて

11

'15 0.5パーセントは」(今週出てくる)0.11.1以降のような文字列としてフォーマットパーセンテージで、置き換える値は、正規表現と交換する新しいオプションを持っているので、これが可能になります

In [14]: df = DataFrame('10.0%',index=range(100),columns=range(10)) 

In [15]: df.replace('%','',regex=True).astype('float')/100 
Out[15]: 
<class 'pandas.core.frame.DataFrame'> 
Int64Index: 100 entries, 0 to 99 
Data columns (total 10 columns): 
0 100 non-null values 
1 100 non-null values 
2 100 non-null values 
3 100 non-null values 
4 100 non-null values 
5 100 non-null values 
6 100 non-null values 
7 100 non-null values 
8 100 non-null values 
9 100 non-null values 
dtypes: float64(10) 

そして受け入れ答えにコメントを答える少し速く

In [16]: %timeit df.replace('%','',regex=True).astype('float')/100 
1000 loops, best of 3: 1.16 ms per loop 

In [18]: %timeit df.applymap(lambda x: float(x[:-1]))/100 
1000 loops, best of 3: 1.67 ms per loop 
+1

はあなたが私に教えてくださいすることができます私は、特定のためにこれを実装する方法列? .astype( 'float')/ 100'は機能しませんでした。 'df [' Column1 ']。replace('% '、' regex = True)。 – erantdo

1
df.applymap(lambda x:float(x.rstrip('%'))/100) 
+1

*若干* 'df1.applymap使用する方が効率的(ラムダX:フロート(のx [: - 1]))/ 100' ... –

1

:特定の列については、を参照してください。

df['Column1'] = df['Column1'].replace('%','',regex=True).astype('float')/100 
関連する問題