![](/img/trans.png)
[英]The column label 'call_id' is not unique. For a multi-index, the label must be a tuple with elements corresponding to each level
[英]Sort dataframe by value returns "For a multi-index, the label must be a tuple with elements corresponding to each level."
Objective: 基於 dataframe 的 5 列,返回 dataframe 的 3 列,其中一列是計數,並按從最大到最小的計數排序。
我試過的:
df = df[['Country', 'Year','NumInstances']].groupby(['Country', 'Year']).agg(['count'])
df = df.sort_values(by='NumInstances', ascending=False)
print(df)
錯誤:ValueError:列 label 'NumInstances' 不是唯一的。 對於多索引,label 必須是一個元組,其元素對應於每個級別。
在這被標記為重復之前,我已經瀏覽了所有其他建議的重復,似乎它們都建議使用與我上面相同的代碼。
我正在做的一些小事情可能不正確嗎?
謝謝!
我想你需要刪除多索引 -
嘗試這個 -
df = df[['Country', 'Year','NumInstances']].groupby(['Country', 'Year']).agg(['count']).reset_index()
或者 -
df = df[['Country', 'Year','NumInstances']].groupby(['Country', 'Year'], as_index=False).agg(['count'])
發現問題。 向 NumInstances 列添加 agg 使 NumInstances 列名稱成為 ('NumInstances', 'sum') 的元組,因此我剛剛將排序代碼更新為:
df = df.sort_values(by=('NumInstances', 'sum'), ascending=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.