python-3.x - 在文本列上使用 Pandas 滚动功能

标签 python-3.x pandas

我有一个 pandas 数据框,其中包含字符串格式的列值和日期时间索引。我想创建一个新列,其中包含过去两天的列值列表。使用 pandas 可以实现这一点吗?

原始数据农场:

        date col1 col2
0 2018-07-08    a    b
1 2018-07-09    c    d
2 2018-07-10    e    f
3 2018-07-11    g    h
4 2018-07-12    i    j
5 2018-07-13    k    l
6 2018-07-14    m    n

最终数据框:

        date col1 col2  col3
0 2018-07-08    a    b   NaN
1 2018-07-09    c    d   NaN
2 2018-07-10    e    f  b, d
3 2018-07-11    g    h  d, f
4 2018-07-12    i    j  f, h
5 2018-07-13    k    l  h, j
6 2018-07-14    m    n  j, l

最佳答案

df.iloc[:,2].shift(2)+ ',' +df.iloc[:,2].shift(1)

编辑

我们可以将其扩展到更通用的设置,

定义自定义滚动连接函数,

rolling_cat = lambda s, n: pd.Series(zip(*[s.shift(x+1) for x in range(n)])).str.join(',')

应用函数

rolling_cat(df.iloc[:,2], n=2)

关于python-3.x - 在文本列上使用 Pandas 滚动功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57657233/

相关文章:

python - pandas read_excel 同一张纸上的多个表

python - 如何标记相同的 Pandas 数据框行?

matplotlib - python生态系统中是否有缺失 map 的实现?

python - Pandas 相对时间轴

python - 如何使用winsound模块同时播放多个频率

python - 尝试按时过滤数据时出现 TypeError ('Index must be DatetimeIndex' )

python - 使用另一列的值切片 Pandas 列

python-3.x - 从内置麦克风获取音频信号

python - 如何在两个模型日期字段之间设置时间增量

python - 这个 List Overlap 程序给出了奇怪的输出