DataFrame.pivot
DataFrame.pivot(index=None, columns=None, values=None)
返回按指定索引或列组织的DataFrame。
基于列值重构数据。使用来自指定索引或列的唯一值来形成DataFrame的轴。
Parameters
index | 用于创建新DataFrame的索引的列。如果为None,则使用现有索引。 |
---|---|
columns | 用于创建新DataFrame的列。 |
values | 用于填充新DataFrame的列。如果未指定,则使用所有剩余列。 |
Example
import pandas as pd
df = pd.DataFrame({'site':['google', 'baidu', 'google', 'baidu'],
'age':[18, 39, 22, 45],
'price': [1.0, 2.0, 3.0, 4.0],
'color': ['red', 'black', 'yellow', 'red']})
df.pivot(index="site", columns="color", values="price")
---------------------------------------------------------------------
color black red yellow
site
baidu 2.0 4.0 NaN
google NaN 1.0 3.0