<p>我用你的示例代码做了一些测试。在</p>
<p><strong>观察1:</strong></p>
<p>这是一个关于该问题的最小可验证代码:</p>
<pre><code>import pandas as pd
from IPython.display import display
#dataset simulate likely input
d = {'vote': [100, 50,1,23,55,67,89,44],
'vote2': [10, 'a',18,55,77,99,9,40],
'ballot1': [1,None,3,4,5,6,7,8],
'voteId':[1,2,3,4,5,6,7,8]}
df1 = pd.DataFrame(d)
#########################################################
df1 = df1.drop_duplicates(['voteId','ballot1'],keep='last')
s = df1[:10].reset_index().set_index(['voteId','ballot1'],verify_integrity=True).unstack()
s.columns=s.columns.map('(ballot1={0[1]}){0[0]}'.format)
dflw=pd.DataFrame(s)
display(dflw)
</code></pre>
<p>假设一下,这些数据可以是我稍微修改一下后发现的(在这个例子的基础上):</p>
^{pr2}$
<p><strong>观察2:</strong></p>
<p>我还制作了另一个数据集(可能更接近您的数据集):</p>
<pre><code>d = {'vote': [10, None,2,23,55,67,89,44],
'vote2': [10,2,3,55,77,99,9,40],
'ballot1': [1,None,3,4,5,6,7,8],
'voteId':['a','b','a','a','c','a','c','a']}
df1 = pd.DataFrame(d)
</code></pre>
<p>有趣的是,ballot1和voteId的顺序与你的情况不同,如果它们的顺序与你的情况相同,就可以了。在</p>
<p>我的观察是,<code>ballot1</code>是一个真正需要cap失败的索引,并且一个投票序列之间需要一个共享值。在</p>
<p><strong>讨论:</strong></p>
<p>如果可能的话,ballot1和voteId(索引)都只有整数,但是ballot1也有一些异常,这取决于投票列中的数据,这个错误可能会引起。在</p>
<p>当索引列值有间隙时,将引发断言,它可能与您的df1[:10]命令有关,例如<a href="https://stackoverflow.com/users/1830793/zev">Zev</a>对<a href="https://github.com/pandas-dev/pandas/issues/19351" rel="nofollow noreferrer">Github</a>上的问题进行了注释。在</p>
<p>在我的例子中,虽然Github建议的解决方法没有效果。最好的办法是去掉数据中的None值,因为数据已经处于良好的状态。在</p>
<p><strong>旁注:</strong></p>
<p><em>我不知道<code>ballot1</code>数据是否允许有整数,但至少如果允许的话,就存在这种情况,在这种情况下可能会发生错误。这些是否有用取决于你的情况,你在写问题的时候还不清楚。现在你至少有一些建议可以尝试。</em></p>