简体   繁体   中英

How to use each row's value as compare object to get the count of rows satisfying a condition from whole DataFrame?

    date    data1
0   2012/1/1    100
1   2012/1/2    109
2   2012/1/3    108
3   2012/1/4    120
4   2012/1/5    80
5   2012/1/6    130
6   2012/1/7    100
7   2012/1/8    140

Given the dataframe above, I want get the number of rows which data1 value is between ± 10 of each row's data1 field, and append that count to each row, such that:

    date    data    Count
0   2012/1/1    100.0   4.0
1   2012/1/2    109.0   4.0
2   2012/1/3    108.0   4.0
3   2012/1/4    120.0   2.0
4   2012/1/5    80.0    1.0
5   2012/1/6    130.0   3.0
6   2012/1/7    100.0   4.0
7   2012/1/8    140.0   2.0

Since each row's field is rule's compare object, I use iterrows , although I know this is not elegant:

result = pd.DataFrame(index=df.index)

for i,r in df.iterrows():
    high=r['data']+10
    low=r['data1']-10
    df2=df.loc[(df['data']<=r['data']+10)&(df['data']>=r['data']-10)]
    result.loc[i,'date']=r['date']
    result.loc[i,'data']=r['data']
    result.loc[i,'count']=df2.shape[0]  
  
result

Is there any more Pandas-style way to do that? Thank you for any help!

Use numpy broadcasting for boolean mask and for count True s use sum :

arr = df['data'].to_numpy()

df['count'] = ((arr[:, None] <= arr+10)&(arr[:, None] >= arr-10)).sum(axis=1)
print (df)
       date  data  count
0  2012/1/1   100      4
1  2012/1/2   109      4
2  2012/1/3   108      4
3  2012/1/4   120      2
4  2012/1/5    80      1
5  2012/1/6   130      3
6  2012/1/7   100      4
7  2012/1/8   140      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