2017-10-31 7 views
1

これは私のコードです!パンダを使用して文字列と番号を分けて追加

import pandas as pd 
df2 = pd.DataFrame({'A': ['1,008$','4,000$','6,000$','10,00$','8,00$','45 €','45 €']}) 

データクリーニングも行われます。私は、この

In [11]: result2 
Out[11]: 
0 1.008 
1 4.000 
2 6.000 
3 10.00 
4  8.00 
5  45 
6  45 
Name: A, dtype: object 

のような出力を提供しますが、私の目的は一緒に異なる通貨の量を追加することです

result2 = df2['A'].str.replace(',','.') 
    result2 = result2.str.replace('$','') 
    result2 = result2.str.replace('€','') 
    print (result2) 

は、その出力は私はないです。この

Your amount in dollar is "29.008" 
your amount in euros is "90" 

ようにする必要がありありPythonで非常に良い、助けてください!

答えて

2

オプション1

df2.A.str.replace(',', '.').str.extract(
    '^(?P<Value>.*)(?P<Currency>\D)$', expand=True 
).apply(pd.to_numeric, errors='ignore').groupby('Currency').Value.sum() 

Currency 
$ 29.008 
€ 90.000 
Name: Value, dtype: float64 

オプション2

v = pd.to_numeric(df2.A.str[:-1].str.replace(',', '.')) 
c = df2.A.str[-1] 

v.groupby(c).sum() 

A 
$ 29.008 
€ 90.000 
Name: A, dtype: float64 

オプション3

d = {'$': 'dollar', '€': 'euro'} 

v = pd.to_numeric(df2.A.str[:-1].str.replace(',', '.')) 
c = df2.A.str[-1].map(d) 

v.groupby(c).sum() 

A 
dollar 29.008 
euro  90.000 
Name: A, dtype: float64 
+0

ありがとう!! TypeError:str_extract()は予期しないキーワード引数 'expand'を持っています –

+0

あなたは古いバージョンのpandasを使用しています。あなたはそれを残すことができます。 – piRSquared

+0

はい、今更新されたパンダ!どうもありがとう !!! が、オプション1と2のために、私は同じエラー 取得しています:オプション1は「とValueError位5 \の文字列を解析することができません 『45 \ XE2の\のX82を』 N」 –

関連する問題