我正在嘗試列印系列中最長的串列并顯示前 10 個長度和相應的串列。
我試著做
df["listoflists"].value_counts()
但它只列印鍵的數量而不是鍵的長度,即串列。我也試過
print(df["listoflists"].applymap(len).idxmax(axis=1))
但是出現錯誤AttributeError: 'Series' object has no attribute 'applymap'如何解決?
uj5u.com熱心網友回復:
假設您有以下資料框:
values = [['a','a'], ['a','b','b','d','e'],
['a','b','b','a'], ['a','b','c','a'],
['a','b','b'],['a','b','b']
df = pd.DataFrame({'listoflists' :values })
對于最長的串列,您可以嘗試:
max(df.listoflists, key=len)
對于前n 個串列,您可以嘗試(在本例中 n = 3):
df['count'] = df.listoflists.map(len)
df.nlargest(3, ['count'])
uj5u.com熱心網友回復:
我將向您展示如何僅對一些隨機資料執行此操作:
# easy random data
df = pd.DataFrame({'listoflists':[[1,2],[3,4,5],[6,7,8,9]]})
# assign back to DataFrame so we can manipulate
df['len'] = df['listoflists'].apply(len)
# then to get top N:
N = 1
df.sort_values(['len'],ascending=False).groupby(['len']).transform(min).head(N)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357487.html
上一篇:如何使用基于整數位置的索引訪問MultiIndex資料幀中的行
下一篇:計數累計真值
