2017-08-22 3 views
3

既存のpandasデータフレームに2つの新しい列を追加しようとしています。私は複数のif else文を持つPython関数を使って実装しました。しかし、私はそれが最良のアプローチではないと思う、もし私が辞書や他のアプローチを同じものを達成するために使用することはできますか?辞書を使用してpandas dfに動的列を追加する効率的な方法を探しています

私は、新しい列を追加するためのコードの下に使用しています:

import pandas as pd 
df = pd.DataFrame({"col_1": [1234567, 45677890, 673214, 6709,98765,'',876543]}) 
def func(col_1): 
    col_1=str(col_1) 

    if col_1=="": 
     return "NA","" 
    elif col_1[0:3]=='123': 
     return "some_text_1 "," other_text_1" 
    elif col_1[0:3]=='456': 
     return "some_text_2 ","other_text_2" 
    elif col_1[0:2]=='67': 
     return "some_text_3 ","other_text_3" 
    elif col_1[0:1]=='9': 
     return "some_text_4 ","other_text_4" 
    else: 
     return "Other","Other" 

df["col_2"],df["col_3"]=zip(*df["col_1"].map(func)) 
print(df) 


     col_1   col_2   col_3 
    0 1234567 some_text_1 other_text_1 
    1 45677890 some_text_2 other_text_2 
    2 673214 some_text_3 other_text_3 
    3  6709 some_text_3 other_text_3 
    4  98765 some_text_4 other_text_4 
    5      NA    
    6 876543   Other   Other  

だから、私は同じことを達成するための最良の方法であるものであれば、複数のとelseステートメントを持っているように、ここで見つけることを試みているものを。私は辞書や他の方法を使用する必要があります、任意のポインタが高く評価されます。

答えて

2

あなたのアプローチは、ベクトル化されていないためにおそらく遅いです。

temp = df['col_1'].astype(str) 
df = df.assign(col_2='Other', col_3='Other') 
df.loc[temp.str[0] == '9', ['col_2', 'col_3']] = ('some_text_4 ', 'other_text_4') 
df.loc[temp.str[0:2] == '67', ['col_2', 'col_3']] = ('some_text_3 ', 'other_text_3') 
df.loc[temp.str[0:3] == '456', ['col_2', 'col_3']] = ('some_text_2 ', 'other_text_2') 
df.loc[temp.str[0:3] == '123', ['col_2', 'col_3']] = ('some_text_1 ', 'other_text_1') 
df.loc[temp == "", ['col_2', 'col_3']] = ("NA", "") 
>>> df 
     col_1   col_2   col_3 
0 1234567 some_text_1 other_text_1 
1 45677890 some_text_2 other_text_2 
2 673214 some_text_3 other_text_3 
3  6709 some_text_3 other_text_3 
4  98765 some_text_4 other_text_4 
5      NA    
6 876543   Other   Other 

考え方は、最も重要でないものを最初に実行するように、if/elseステートメントの順序を逆にすることです。後続のルールが優先され、その上のルールを上書きする可能性があります。

+0

ディクショナリを使用して同じものを実装する方法はありますか? – user07

+0

また、あなたのソリューションはここで一時的なものは動作していません?それはcol_1の値ですか? – user07

+0

'temp = df ['col_1']。astype(str)'です。 – Alexander

関連する問題