如何确定哪些ID在Python数据帧的另一列中的值随时间而增加?

2024-05-05 20:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个包含3列的数据框:

| id | value |    date   |
+====+=======+===========+
|  1 |   50  |  1-Feb-19 |
+----+-------+-----------+
|  1 |  100  |  5-Feb-19 |
+----+-------+-----------+
|  1 |  200  |  6-Jun-19 |
+----+-------+-----------+
|  1 |  500  |  1-Dec-19 |
+----+-------+-----------+
|  2 |   10  |  6-Jul-19 |
+----+-------+-----------+
|  3 |  500  |  1-Mar-19 |
+----+-------+-----------+
|  3 |  200  |  5-Apr-19 |
+----+-------+-----------+
|  3 |  100  | 30-Jun-19 |
+----+-------+-----------+
|  3 |   10  | 25-Dec-19 |
+----+-------+-----------+

ID列包含特定人员的ID。 值列包含其事务的值。 “日期”列包含其交易的日期

Python中有没有一种方法可以将ID1标识为随着时间推移事务值不断增加的ID

我正在寻找一些方法,我可以提取ID 1作为我想要的ID,随着事务值的增加,过滤掉ID 2,因为它没有足够的事务来分析趋势,还可以过滤掉ID 3,因为它的事务趋势随着时间的推移而下降


Tags: 数据方法iddate人员value事务趋势
2条回答
df['new'] = df.groupby(['id'])['value'].transform(lambda x : \
                      np.where(x.diff()>0,'incresase',
                      np.where(x.diff()<0,'decrease',' ')))

df = df.groupby('id').new.agg(['last'])
df

输出:

      last
id  
1   increase
2    
3   decrease

仅增加ID:

increasingList = df[(df['last']=='increase')].index.values
print(increasingList)

结果:

[1]

假设这不会发生

1  50
1  100
1  50

如果是,那么:

df['new'] = df.groupby(['id'])['value'].transform(lambda x : \
                      np.where(x.diff()>0,'increase',
                      np.where(x.diff()<0,'decrease',' ')))
df

输出:

    value   new
id      
1   50   
1   100 increase
1   200 increase
2   10   
3   500  
3   300 decrease
3   100 decrease

Concat字符串:

df = df.groupby(['id'])['new'].apply(lambda x: ','.join(x)).reset_index()
df

中间结果:

    id  new
0   1    ,increase,increase
1   2    
2   3    ,decrease,decrease

检查行中是否存在减少/仅存在“”。放下它们

df = df.drop(df[df['new'].str.contains("dec")].index.values)
df = df.drop(df[(df['new']==' ')].index.values)
df

结果:

    id  new
0   1    ,increase,increase

可以按id分组,并检查排序的值是否相同,无论是按值排序还是按日期排序:

>>> df.groupby('id').apply( lambda x:
...    (
...        x.sort_values('value', ignore_index=True)['value'] == x.sort_values('date', ignore_index=True)['value']
...    ).all()
... )
id
1     True
2     True
3    False
dtype: bool

编辑:

要使id=2不为真,我们可以这样做:

>>> df.groupby('id').apply( lambda x:
...    (
...        (x.sort_values('value', ignore_index=True)['value'] == x.sort_values('date', ignore_index=True)['value'])
...        & (len(x) > 1)
...    ).all()
... )
id
1     True
2    False
3    False
dtype: bool

相关问题 更多 >