如何将数据帧行转换为标题?

时间:2016-07-28 05:47:57

标签: python pandas

我在151个不同数据帧的前151个口袋妖怪中都有一些数据。

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

我真正想要的是每个口袋妖怪一行,每个属性作为新数据帧的一列。像

这样的东西
unless

使用pandas数据帧有没有简单的方法呢?

2 个答案:

答案 0 :(得分:4)

我相信这会做你以后的事情:

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

答案 1 :(得分:1)

您可以使用pivot_table

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 comprehension使用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

reset_index

上次使用pandasconcat0.18.0 pandas bellow 0.18.0中的新内容),如果使用rename_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 }:

XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_ur…d=410427634474-u3tpasmj4r80s6v20o54s85fikhotl79.apps.googleusercontent.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.