gpt4 book ai didi

python - 在 pandas 滚动函数上获取 CSV 值

转载 作者:行者123 更新时间:2023-12-02 18:35:56 28 4
gpt4 key购买 nike

我试图以滚动方法获取给定窗口的值的 csv 输出,但收到错误必须是实数,而不是 str

看来输出必须是数字类型。 https://github.com/pandas-dev/pandas/issues/23002

df = pd.DataFrame({"a": range(1,10)})
df.head(10)

# Output
a
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

尝试过:

to_csv = lambda x: x.to_csv(index=False)
# to_csv = lambda x: ",".join([str(d) for d in x])
df["running_csv"] = df.rolling(min_periods=1, window=3).apply(to_csv) # <= Causes Error

# Error:
# TypeError: must be real number, not str

预期输出

    a   running_csv
0 1 1
1 2 1,2
2 3 1,2,3
3 4 2,3,4
4 5 3,4,5
5 6 4,5,6
6 7 5,6,7
7 8 6,7,8
8 9 7,8,9

问题:是否有其他方法可以获取如上所示的 CSV 输出?

最佳答案

类似这样的吗?

>>> df['running_csv'] = pd.Series(df.rolling(min_periods=1, window=3)).apply(lambda x:x.a.values)
>>> df
a running_csv
0 1 [1]
1 2 [1, 2]
2 3 [1, 2, 3]
3 4 [2, 3, 4]
4 5 [3, 4, 5]
5 6 [4, 5, 6]
6 7 [5, 6, 7]
7 8 [6, 7, 8]
8 9 [7, 8, 9]

从这里开始,进一步的处理应该很容易。

关于python - 在 pandas 滚动函数上获取 CSV 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68777915/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com