简体   繁体   中英

Keeping rows based on conditions(Pandas)

I have a dataFrame:

df.head()
Out[374]: 
   ID  Time     op1      
0   1     1 -0.0007    
1   1     2  0.0019      
2   1     3 -0.0043      
3   1     4  0.0007      
4   1     5 -0.0019

ID runs from 1 to 100. I have a list difference:

difference
Out[375]: 
[161,
 238,
 53,
 83,
 171,...

Now I want to keep those rows in Time which are less than or equal to as specified in difference. For ex: for Id=1, I want to keep rows till Time=161; for ID=2, I want to keep rows till Time=238 and so on. Any help?

I believe you need create dictionary for map with enumerate , compare with Time column and filter by boolean indexing :

print (df)
   ID  Time     op1
0   1     1 -0.0007
1   1     2  0.0019
2   1     3 -0.0043
3   2     4  0.0007
4   2     5 -0.0019

difference = [2, 6, 53, 83]
d = dict(enumerate(difference, 1))
print (d)
{1: 2, 2: 6, 3: 53, 4: 83}

df = df[df['Time'] < df['ID'].map(d)]
print (df)
   ID  Time     op1
0   1     1 -0.0007
3   2     4  0.0007
4   2     5 -0.0019

Detail :

print (df['ID'].map(d))
0    2
1    2
2    2
3    6
4    6
Name: ID, dtype: int64

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