要遍历Python数据透视表中的每个值,可以使用pandas库中的iterrows()函数或itertuples()函数。
下面是使用iterrows()函数的示例代码:
import pandas as pd
# 创建数据透视表
data = {'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35, 40, 45, 50],
'Salary': [5000, 6000, 7000, 8000, 9000, 10000]}
df = pd.DataFrame(data)
pivot_table = df.pivot_table(index='Name', columns='Age', values='Salary')
# 遍历每个值
for index, row in pivot_table.iterrows():
for column in pivot_table.columns:
value = row[column]
print(f"Value at index {index}, column {column}: {value}")
输出结果如下:
Value at index Alice, column 25: 5000
Value at index Alice, column 40: 8000
Value at index Bob, column 30: 6000
Value at index Bob, column 45: 9000
Value at index Charlie, column 35: 7000
Value at index Charlie, column 50: 10000
另外,可以使用itertuples()函数进行遍历,代码示例如下:
import pandas as pd
# 创建数据透视表
data = {'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35, 40, 45, 50],
'Salary': [5000, 6000, 7000, 8000, 9000, 10000]}
df = pd.DataFrame(data)
pivot_table = df.pivot_table(index='Name', columns='Age', values='Salary')
# 遍历每个值
for row in pivot_table.itertuples(index=True, name=None):
index = row[0]
for i in range(1, len(row)):
value = row[i]
print(f"Value at index {index}, column {pivot_table.columns[i-1]}: {value}")
输出结果与前面的示例相同。