2016-07-28 5 views
1

151の異なるデータフレームで最初の151ポケモンのそれぞれにいくつかのデータがあります。データフレームの行をヘッダーに変換するにはどうすればよいですか?

id identifier pokemon_id stat_id base_stat local_language_id name 
36 7 Squirtle 7 1 44 9 HP 
37 7 Squirtle 7 2 48 9 Attack 
38 7 Squirtle 7 3 65 9 Defense 
39 7 Squirtle 7 4 50 9 Special Attack 
40 7 Squirtle 7 5 64 9 Special Defense 
41 7 Squirtle 7 6 43 9 Speed 


    id identifier pokemon_id stat_id base_stat local_language_id name 
18 4 Charmander 4 1 39 9 HP 
19 4 Charmander 4 2 52 9 Attack 
20 4 Charmander 4 3 43 9 Defense 
21 4 Charmander 4 4 60 9 Special Attack 
22 4 Charmander 4 5 50 9 Special Defense 
23 4 Charmander 4 6 65 9 Speed 

私が本当に気に入っているのは、ポケモンごとに1つの行が各データを新しいデータフレームの列として表示することです。何かのように

id identifier pokemon_id HP Attack ... 
4  Charmander 4   39 52  ... 
7  Squirtle  7   44 48  ... 

パンダのデータフレームで簡単に行う方法はありますか?

答えて

4

私は、これはあなたが後にしている何だろうと信じて:あなたはpivot_tableを使用することができます

df.groupby(['id', 'identifier', 'name']).base_stat.first().unstack('name') 
+0

グレート、ありがとう!私は 'pivot_tables'を試していた –

+0

グループ/アンスタックは基本的にピボットテーブルと同じです。 – Alexander

1

df = df.pivot_table(index=['id','identifier'], 
        columns='name', 
        values='base_stat', 
        aggfunc='first') 

print (df) 
name   Attack Defense HP Special Attack Special Defense Speed 
id identifier                
7 Squirtle  48  65 44    50    64  43 

すべてDataFramesがリストdfsにある場合、list comprehensionconcatを使用します。

dfs = [df1, df2] 

df = pd.concat([df.pivot_table(index=['id','identifier'], 
           columns='name', 
           values='base_stat', 
           aggfunc='first') for df in dfs]) 
print (df) 
name   Attack Defense HP Special Attack Special Defense Speed 
id identifier                
7 Squirtle  48  65 44    50    64  43 
4 Charmander  52  43 39    60    50  65 

最終使用(pandas0.18.0の新機能)と、使用pandas bellow 0.18.0rename_axisを省略しdf.columns.name = Noneを使用している場合:

df = pd.concat([df.pivot_table(index=['id','identifier'], 
           columns='name', 
           values='base_stat', 
           aggfunc='first') for df in dfs]) 
        .reset_index() 
        .rename_axis(None, axis=1) 
print (df) 
    id identifier Attack Defense HP Special Attack Special Defense Speed 
0 7 Squirtle  48  65 44    50    64  43 
1 4 Charmander  52  43 39    60    50  65 
関連する問題