我想創建一個串列,該串列計算資料幀中每個相同行的零迭代。
Id_1 Id_2
0 1401 1
1 1401 1
2 1801 0
3 1801 0
4 1801 0
5 1801 0
6 2001 1
7 2001 1
8 2201 0
9 2201 0
# I would like this output:
L = [(1801, 4), (2201, 2)]
uj5u.com熱心網友回復:
您可以像這樣在一行中完成這項作業:
L = list(df[df['Id_2'] == 0].groupby(['Id_1']).count().to_records())
輸出:
[(1801, 4), (2201, 2)]
uj5u.com熱心網友回復:
按DataFrame.locwith過濾值Series.value_counts并轉換Series為元組串列:
L = [(a, b) for a, b in df.loc[df['Id_2'].eq(0), 'Id_1'].value_counts().items()]
print (L)
[(1801, 4), (2201, 2)]
或者:
L = list(df.loc[df['Id_2'].eq(0), 'Id_1'].value_counts().to_frame().to_records())
print (L)
[(1801, 4), (2201, 2)]
或者:
L = (df.loc[df['Id_2'].eq(0), 'Id_1']
.value_counts()
.to_frame(0)
.set_index(0, append=True)
.index
.tolist())
print (L)
[(1801, 4), (2201, 2)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375925.html
上一篇:使用Prolog檢查IP地址串列
