【发布时间】:2019-06-02 12:59:54
【问题描述】:
大量更新的问题:我发现了导致错误的问题:数据框包含一些空列。添加了一个可重现的示例。
我有一个看起来像这样但更大 (2500x288) 的 Pandas DataFrame:
df = pd.DataFrame(np.random.randn(3, 8),
columns=pd.MultiIndex.from_arrays((['A','A','A', 'A', 'B', 'B', 'B', 'B'],
['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'],
['i', 'ii', 'i', 'ii', 'i', 'ii', 'i', 'ii'])))
A B
a b c d a b c d
i ii i ii i ii i ii
0 -0.344673 0.711897 -1.306805 -1.926644 -0.351334 -0.864423 -1.023401 -0.284710
1 0.730107 0.245481 -0.570591 1.740258 0.779193 -0.151460 2.082086 -0.008099
2 -0.806092 -1.364315 0.845041 1.739843 0.737802 -2.232088 0.114731 -1.028346
现在我想在 MultiIndex 列的两个级别上求和,例如:
df.sum(level=[1,2], axis=1)
a b c d
i ii i ii
0 -0.696007 -0.152525 -2.330206 -2.211354
1 1.509300 0.094021 1.511495 1.732159
2 -0.068290 -3.596403 0.959772 0.711497
但是,一旦列为空,就会出现 ValueError。
df.loc[:, ('A','b','ii')] = None
df.sum(level=[1,2], axis=1)
ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'
单级求和有效(例如df.sum(level=1, axis=1))。此外,using transpose(),例如df.transpose().sum(level=[1,2], axis=0).transpose() 可以工作,尽管速度非常慢。这告诉我这可能更像是一个错误,而不是我“做错了”。
使用df.groupby(level=[1,2], axis=1).sum() 会出现同样的错误。
【问题讨论】:
-
@ALollz 是的,因为转置两次使用相同的 df
-
嗨,你用的是什么版本的
pandas,df的维数是多少,你开始遇到这个问题 -
@GrigoriyMikhalkin DF 有 2500 行 x 288 列。 Pandas 在 Python 3.7.2 上是 0.23.4。我希望我今天能找到更多时间来玩 df,看看问题何时开始出现。到目前为止,我完全一无所知。
-
生成的 df 包含 100000 行 x 676 列:
df = pd.DataFrame(np.random.randn(100000, len(string.ascii_lowercase) * len(string.ascii_uppercase)), columns=pd.MultiIndex.from_arrays((list(itertools.chain(*[[l] * len(string.ascii_lowercase) for l in string.ascii_uppercase])), [l for i in range(len(string.ascii_uppercase)) for l in string.ascii_lowercase], ['i' if ord(l) % 2 == 1 else 'ii' for i in range(len(string.ascii_uppercase)) for l in string.ascii_lowercase])))。总和仍然有效。似乎问题不在于尺寸。 -
@GrigoriyMikhalkin 我发现了问题!事实是 df 有空列。
标签: python pandas multi-index