2016-05-20 9 views
1

データフレームDFは量DataFrameの列内のすべての値を解析する方法は?

import pandas as pd 
df = pd.DataFrame(['$3,000,000.00','$3,000.00', '$200.5', '$5.5'], columns = ['Amount']) 

DFというカラムがあります。

ID | Amount 
0 | $3,000,000.00 
1 | $3,000.00 
2 | $200.5 
3 | $5.5 

を私はコラム量のすべての値を解析し、数値として量を抽出し、小数点を無視したいです。最終結果は次のようなDataFrameです。

ID | Amount 
0 | 3000000 
1 | 3000 
2 | 200 
3 | 5 

どうすればよいですか?

答えて

4

あなたはastypeでダブルキャストでstr.replaceを使用することができます。

df['Amount'] = (df.Amount.str.replace(r'[\$,]', '').astype(float).astype(int)) 
print (df) 
    Amount 
0 3000000 
1  3000 
2  200 
3  5 
1

コード -

import pandas as pd 

def format_amount(x): 
    x = x[1:].split('.')[0] 
    return int(''.join(x.split(','))) 

df = pd.DataFrame(['$3,000,000.00','$3,000.00', '$200.5', '$5.5'], columns = 
     ['Amount']) 

df['Amount'] = df['Amount'].apply(format_amount) 

print(df) 

出力 -

Amount 
0 3000000 
1  3000 
2  200 
3  5 
3

あなたが列にマップ機能を使用し、同じ列に再割り当てする必要があります。

import locale 
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 

df.Amount = df.Amount.map(lambda s: int(locale.atof(s[1:]))) 

PS:これは、使用していますHow do I use Python to convert a string to a number if it has commas in it as thousands separators?のコードは、桁区切りの数値を表す文字列をintに変換する

+0

私はバージョン 'パンダ0.18.2'、' pythonでそれをテスト:3.5.1'.and 'とValueError:float型に文字列を変換できませんでした: '3,000,000.00' '私は 'import locale print(df.Amount.map(lambda:int(locale.atof(s [1:])))')を使います。何が問題なのでしょうか?たぶん、pandas APIが変更されました。たぶん誰かが試してみるかもしれない。 – jezrael

+0

番号を解析する前に、 'locale.setlocale(locale.LC_ALL、 'en_US.UTF-8')'が必要です。 –

+0

私はそれを試して、今は 'エラー:サポートされていないロケール設定'です。 – jezrael

関連する問題