Python|熊猫.pivot()
pandas.pivot(index, columns, values)函数根据 DataFrame 的 3 列生成数据透视表。使用索引/列中的唯一值并用值填充。
Parameters:
index[ndarray] : Labels to use to make new frame’s index
columns[ndarray] : Labels to use to make new frame’s columns
values[ndarray] : Values to use for populating new frame’s values
Returns: Reshaped DataFrame
Exception: ValueError raised if there are any duplicates.
代码:
# Create a simple dataframe
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['John', 'Boby', 'Mina'],
'B': ['Masters', 'Graduate', 'Graduate'],
'C': [27, 23, 21]})
df
# values can be an object or a list
df.pivot('A', 'B', 'C')
# value is a list
df.pivot(index ='A', columns ='B', values =['C', 'A'])
当有任何索引、具有多个值的列组合时引发 ValueError。
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['John', 'John', 'Mina'],
'B': ['Masters', 'Masters', 'Graduate'],
'C': [27, 23, 21]})
df.pivot('A', 'B', 'C')
ValueError: Index contains duplicate entries, cannot reshape