📜  Python|熊猫.pivot()

📅  最后修改于: 2022-05-13 01:55:48.413000             🧑  作者: Mango

Python|熊猫.pivot()

pandas.pivot(index, columns, values)函数根据 DataFrame 的 3 列生成数据透视表。使用索引/列中的唯一值并用值填充。

代码:

# 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