如何从现有数据帧中创建数据帧中的上一列和下一列?

2023-12-21

所以,假设我有一个这样的数据框。

df = pd.DataFrame({'person':['A', 'A', 'B', 'B', 'A'],
                   'datetime':['2018-02-26 10:49:32', '2018-02-26 10:58:03', '2018-02-26 10:51:10','2018-02-26 10:58:45', '2018-02-26 10:43:34'], 
                   'location':['a', 'b', 'c', 'd', 'e']})

这表明

person  datetime    location
    A   2018-02-26 10:49:32 a
    A   2018-02-26 10:58:03 b
    B   2018-02-26 10:51:10 c
    B   2018-02-26 10:58:45 d
    A   2018-02-26 10:43:34 e

然后我根据每个人和每个时间进行排序

df.sort_values(by=['person', 'datetime'])

这将按每个人的时间对他们的活动进行排序。

person  datetime    location
4   A   2018-02-26 10:43:34 e
0   A   2018-02-26 10:49:32 a
1   A   2018-02-26 10:58:03 b
2   B   2018-02-26 10:51:10 c
3   B   2018-02-26 10:58:45 d

可以理解为人 A 从地点 e 出发,然后前往 a,然后前往 b。与此同时,B 从地点 c 前往地点 d。

我想创建一个跟踪每个人的动作的数据框,就像这样。

| person | prev_datetime       | prev_loc | next_datetime       | next_loc |
|--------|---------------------|----------|---------------------|----------|
| A      | 2018-02-26 10:43:34 | e        | 2018-02-26 10:49:32 | a        |
| A      | 2018-02-26 10:49:32 | a        | 2018-02-26 10:58:03 | b        |
| B      | 2018-02-26 10:51:10 | c        | 2018-02-26 10:58:45 | d        |

我真的不知道如何做到这一点。谢谢。


Use DataFrameGroupBy.shift http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html2 列,最后删除最后重复的行person列依据Series.duplicated http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html with rename列:

df['datetime'] = pd.to_datetime(df['datetime'])
df1 = df.sort_values(by=['person', 'datetime'])

df1[['next_datetime','next_loc']] = df1.groupby('person')['datetime','location'].shift(-1)
d = {'datetime':'prev_datetime','location':'prev_loc'}
df2 = df1[df1['person'].duplicated(keep='last')].rename(columns=d)
print (df2)
  person       prev_datetime prev_loc       next_datetime next_loc
4      A 2018-02-26 10:43:34        e 2018-02-26 10:49:32        a
0      A 2018-02-26 10:49:32        a 2018-02-26 10:58:03        b
2      B 2018-02-26 10:51:10        c 2018-02-26 10:58:45        d
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从现有数据帧中创建数据帧中的上一列和下一列? 的相关文章

随机推荐