データフレームに特定の列があるとします。一部のフィールドには1つの値しか含まれていませんが、10の値も含まれています。
data["golden_globes_nominee_categories"].str.split(";")
その後、私はこのように行を繰り返しました。
for index, row in data.iterrows():
print (row["golden_globes_nominee_categories"])
そしてこれを得た:
["Best Original Song - Motion Picture ", " Best Performance by an Actor in a Motion Picture - Comedy or Musical"]
["Best Original Score - Motion Picture ", " Best Performance by an Actress in a Motion Picture - Drama"]
...
それから私はこのように各要素をループしました:
for index, row in data.iterrows():
for x in row["golden_globes_nominee_categories"]:
しかし今、私は本当にそれがセルで言及されている場合私に表示される数字(1または0)を含むすべての特定の値に対して列を作成する方法に興味がありますか?
基本的に私はこのようなことをしたいです。
dataframe["time_sp_comp2"] = dataframe["time_spend_company"].apply(lambda x: 1 if x==2 else 0)
dataframe["time_sp_comp3"] = dataframe["time_spend_company"].apply(lambda x: 1 if x==3 else 0)
dataframe["time_sp_comp4"] = dataframe["time_spend_company"].apply(lambda x: 1 if x==4 else 0)
dataframe.drop("time_spend_company", axis=1, inplace=True)
回答:
回答№1は1私 思う これがあなたが求めるものです。
データの例
df = pd.DataFrame({"name": ["Jack", "Jill", "Chad"] ,
"tags": ["tall;rich;handsome",
"short;rich;pretty",
"tall"]})
df
name tags
0 Jack tall;rich;handsome
1 Jill short;rich;pretty
2 Chad tall
タグ文字列を分割し、ダミー変数を取得する pd.get_dummies
)
result = pd.DataFrame({k:1 for k in t}
for t in df.tags.str.split(";")).fillna(0).astype(int)
result
handsome pretty rich short tall
0 1 0 1 0 1
1 0 1 1 1 0
2 0 0 0 0 1
名前とダミー変数をマージする
pd.concat([df["name"], result], axis=1)
name handsome pretty rich short tall
0 Jack 1 0 1 0 1
1 Jill 0 1 1 1 0
2 Chad 0 0 0 0 1