Last active
August 29, 2015 14:07
-
-
Save dogrunjp/41a2ac6eceb6ceed55ea to your computer and use it in GitHub Desktop.
pandasのDataFrameの値を他の配列を参照して条件付きで操作するスクリプトを考えてみました。この例では辞書的に「名字のリスト」をarrayとして参照しながら、姓ー名の入ったデータ項目の荒いバリデーションを実装しています。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#firstname-lastnameのデータフレームからユニークな名字をndarrayとして | |
#取り出します。このデータはバリデーションされているものとします。 | |
lastname = pd.unique(name.lastnames) | |
#何らかのソースより名前-名字のデータフレームを生成 | |
df = pd.DataFrame(nameDB, column = ['first_name', 'last_name']) | |
#isinメソッドを使って条件付きでデータをdf["first_name"]に代入します。 | |
#ここで下記のように記述するとSettingWithCopyWarningと警告され正しい値が入力されません。 | |
df[df["first_name"].isin(artistcount)]["first_name"] = df['last_name'] | |
#正しい記述は下記とおり | |
#部分的にfirst_nameを入れ替えてしまうのではじめにカラムを複製しておきます。 | |
df['new_name'] = df['first_name'] | |
#isinメソッドでlastname配列にfirst_nameが含まれる場合、同じ行のlast_nameの値で置換します。 | |
df.loc[df["first_name"].isin(lastname),"first_name"] = df['last_name'] | |
#同様に等号を使った条件付き参照でfirst_nameとlast_nameが等しくなった行の | |
#lastnameをおきかえます。 | |
df.loc[df["first_name"] == df["last_name"],"last_name"] = df['new_name'] | |
df = df.drop('new_name', 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment