次のデータフレームがあるとしましょう。
fix_id lg home_team away_team
9887 30 Leganes Alaves
9886 30 Valencia Las Palmas
9885 30 Celta Vigo Real Sociedad
9884 30 Girona Atletico Madrid
そして、データフレームのすべての行に対して適用関数を実行します。適用関数の出力は、次のパンダシリーズです。
9887 ({'defense': '74', 'midfield': '75', 'attack': '74', 'overall': '75'},
{'defense': '74', 'midfield': '75', 'attack': '77', 'overall': '75'}),
9886 ({'defense': '80', 'midfield': '80', 'attack': '80', 'overall': '80'},
{'defense': '75', 'midfield': '74', 'attack': '77', 'overall': '75'}),
...
出力ディクショナリを新しい列としてデータフレームに追加するにはどうすればよいですか。8つすべてを同じ行に追加したいと思います。
ご案内をいただければ幸いです。必ずしもコードではありません。たぶん、その方法を教えてくれれば、やってみますか?
ありがとう。
出力がシリーズに保存されているs
とすると、次のことができます。
pd.concat([df, s.apply(pd.Series)[0].apply(pd.Series), s.apply(pd.Series)[1].apply(pd.Series)], axis=1)
例
df = pd.DataFrame({'lg': {9887: 30, 9886: 30, 9885: 30, 9884: 30}, 'home_team': {9887: 'Leganes', 9886: 'Valencia', 9885: 'Celta Vigo', 9884: 'Girona'}, 'away_team': {9887: 'Alaves', 9886: 'Las Palmas', 9885: 'Real Sociedad', 9884: 'Atletico Madrid'}})
s = pd.Series({9887: ({'defense': '74', 'midfield': '75', 'attack': '74', 'overall': '75'}, {'defense': '74', 'midfield': '75', 'attack': '77', 'overall': '75'}), 9886: ({'defense': '80', 'midfield': '80', 'attack': '80', 'overall': '80'}, {'defense': '75', 'midfield': '74', 'attack': '77', 'overall': '75'})})
print(df)
# lg home_team away_team
#9887 30 Leganes Alaves
#9886 30 Valencia Las Palmas
#9885 30 Celta Vigo Real Sociedad
#9884 30 Girona Atletico Madrid
print(s)
#9887 ({'defense': '74', 'midfield': '75', 'attack':...
#9886 ({'defense': '80', 'midfield': '80', 'attack':...
#dtype: object
df = pd.concat([df, s.apply(pd.Series)[0].apply(pd.Series), s.apply(pd.Series)[1].apply(pd.Series)], axis=1)
# lg home_team away_team defense ... defense midfield attack overall
#9884 30 Girona Atletico Madrid NaN ... NaN NaN NaN NaN
#9885 30 Celta Vigo Real Sociedad NaN ... NaN NaN NaN NaN
#9886 30 Valencia Las Palmas 80 ... 75 74 77 75
#9887 30 Leganes Alaves 74 ... 74 75 77 75
[4 rows x 11 columns]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加