简体   繁体   中英

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.

    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:

[(1801, 4), (2201, 2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM