2017-11-21 18 views
1

申し訳ありませんが、NOOBはここにあります! DataFrameのインデックス列の一部の文字列値を置換しようとしています。インデックスは国名であり、「英国と北アイルランド」のようなものを「英国」に置き換える必要があります。PythonのDataFrameインデックス値を条件付き引数に置き換える

は、データフレームは以下のようになります。私は試してみました

data = ['12','13','14', '15'] 
df = pd.DataFrame(data, index = ['Republic of Korea','United States of America20', 'United Kingdom of Great Britain and Northern Ireland19','China, Hong Kong Special Administrative Region'],columns=['Country']) 

:私は確かにその非常に簡単だし、それを実行する方法のために広範囲に検索しました

d={"Republic of Korea": "South Korea", 
    "United States of America20": "United States", 
    "United Kingdom of Great Britain and Northern Ireland19": "United Kingdom", 
    "China, Hong Kong Special Administrative Region": "Hong Kong"} 
df.index = df.index.str.replace(d) 

。 replaceが位置引数を欠いているというエラーメッセージを取得するだけです。

答えて

0

が機能rename使用されている:私にとって

df = df.rename(d) 
print (df) 
       Country 
South Korea   12 
United States  13 
United Kingdom  14 
Hong Kong   15 

をタイミングが実質的に同じです。

df = pd.concat([df] * 100000) 

In [11]: %timeit df.rename(d) 
10 loops, best of 3: 75.7 ms per loop 

In [12]: %timeit pd.Series(df.index).replace(d) 
10 loops, best of 3: 71.8 ms per loop 

In [13]: %timeit pd.Series(df.index.values).replace(d) 
10 loops, best of 3: 75.3 ms per loop 
+0

'pd.Series(df.index.values).replace(d)'をあなたのタイムリストにも追加できますか? –

+1

もちろん、問題ありません。完了しました。 – jezrael

1

あなたはシリーズを初期化し、pd.Series.replaceを呼び出すことができます。私はdf.index.valuesを使用して、よりスピードを絞り出すことができ

df 
                Country 
Republic of Korea          12 
United States of America20        13 
United Kingdom of Great Britain and Northern Ir...  14 
China, Hong Kong Special Administrative Region   15 


df.index = pd.Series(df.index).replace(d) 
df 

       Country 
South Korea   12 
United States  13 
United Kingdom  14 
Hong Kong   15 

タイミング

df = pd.concat([df] * 100000) 

%timeit df.rename(d) 
10 loops, best of 3: 116 ms per loop 

%timeit pd.Series(df.index).replace(d) 
10 loops, best of 3: 96.7 ms per loop 

%timeit pd.Series(df.index.values).replace(d) 
10 loops, best of 3: 88 ms per loop 

タイミングはお使いのマシンによって異なりますので、どの方法を使用するかを決める前に独自のテストを行ってください。 indexまたはcolumnsreplaceの値のパンダで

+0

うーん、あなたのパンダのバージョンは何ですか?私もタイミングをテストし、それは非常に似ています。私は 'win7'の' 0.21.0'を 'python3'で使います。 – jezrael

+0

@jezrael 0.21 on python3.4(Ipython5)、MacOS。私のマシンは少し古いので、タイミングは変わります。 –

+0

ご協力ありがとうございます。すべての代替案を見るのは嬉しい –

関連する問題