使用Pandas DataFrame生成透视表返回空表的问题求助
问题解决:透视表返回空表的原因及修复方法
问题原因
你的透视表返回空表,核心原因是pd.pivot_table()默认参数dropna=True——这个参数会自动剔除**索引(index)或列(columns)中包含空值(NaN)**的行。看你的数据:
- 所有A='a1'的行,B列全为NaN
- 所有A='a2'的行,E列全为NaN
所以所有行都被过滤掉,最终生成空表。
修复代码
只需在pivot_table中显式设置dropna=False,保留包含空值的索引项:
import pandas as pd import numpy as np data = pd.DataFrame( {'A': {0: 'a1', 1: 'a1', 2: 'a1', 3: 'a1', 4: 'a1', 5: 'a2', 6: 'a2', 7: 'a2', 8: 'a2', 9: 'a2'}, 'B': {0: np.nan, 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan, 5: 'bb', 6: 'bc', 7: 'bd', 8: 'be', 9: 'bf'}, 'col': {0: 10, 1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 7: 10, 8: 10, 9: 10}, 'C': {0: 'c1', 1: 'c1', 2: 'c1', 3: 'c1', 4: 'c1', 5: 'c2', 6: 'c2', 7: 'c2', 8: 'c2', 9: 'c2'}, 'D': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}, 'E': {0: 'e1', 1: 'e2', 2: 'e3', 3: 'e4', 4: 'e5', 5: np.nan, 6: np.nan, 7: np.nan, 8: np.nan, 9: np.nan}} ) # 修改后的透视表代码 pivot = pd.pivot_table(data, values='D', index=['A', 'B', 'C', 'E'], columns=['col'], dropna=False) print(pivot)
输出结果
执行后会得到包含所有预期行的透视表,示例输出如下:
col 10 A B C E a1 NaN c1 e1 0 e2 0 e3 0 e4 0 e5 0 a2 bb c2 NaN 0 bc c2 NaN 0 bd c2 NaN 0 be c2 NaN 0 bf c2 NaN 0
内容的提问来源于stack exchange,提问作者Nonancourt
相关产品推荐
相关产品推荐

