python - Getting lists of indices from pandas dataframe -
i'm trying list of indices out of pandas dataframe.
first import.
import pandas pd
construct pandas dataframe.
# create dataframe data = {'name': ['jason', 'jason', 'tina', 'tina', 'tina', 'jason', 'tina'], 'reports': [4, 24, 31, 2, 3, 5, 10], 'coverage': [true, false, false, false, true, true, false]} df = pd.dataframe(data) print(df)
output:
coverage name reports 0 true jason 4 1 false jason 24 2 false tina 31 3 false tina 2 4 true tina 3 5 true jason 5 6 false tina 10
i have indices on left of dataframe when coverage set true, have every name separately. preferably without explicit for-loop.
desired output this.
list_jason = [0, 5] list_tina = [4]
attempted solution: thought should use 'groupby' , access coverage column. there don't know how proceed. appreciated.
df.groupby('name')['coverage']
you want index out each group.
this stored in 'groups' attribute of groupbydataframe.
#filter coverage==true #group 'name' #access 'groups' attribute by_person = df[df.coverage].groupby('name').groups
will return:
{'jason': int64index([0, 5], dtype='int64'), 'tina': int64index([4], dtype='int64')}
from can access individuals regular dictionary:
by_person['jason']
returns:
int64index([0, 5], dtype='int64')
which can treat regular list.
wiki
Comments
Post a Comment