[英]How to create list that return the occurences of zeros in a dataframe?
I want to creat list thats counts the iterration of zeros for every same rows in a dataframe.我想创建一个列表,它计算 dataframe 中每个相同行的零迭代。
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)]
Use:利用:
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)]
Or:或者:
L = list(df.loc[df['Id_2'].eq(0), 'Id_1'].value_counts().to_frame().to_records())
print (L)
[(1801, 4), (2201, 2)]
Or:或者:
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)]
You can do the job in one line like this:您可以像这样在一行中完成这项工作:
L = list(df[df['Id_2'] == 0].groupby(['Id_1']).count().to_records())
output: output:
[(1801, 4), (2201, 2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.