gpt4 book ai didi

python - 是否有一个 Pandas 函数可以将例如前三行连接在一起(就像我有一个长度为三的窗口)

转载 作者:行者123 更新时间:2023-12-04 08:01:09 24 4
gpt4 key购买 nike

例如我有下面的数据帧

df13 = pd.DataFrame(np.random.randint(1,9, size=(5,3)), 
columns=['a','b','c'])
df13
   a  b  c
0 8 5 2
1 5 7 7
2 3 7 5
3 7 7 7
4 2 2 6
并且想要
      a     b     c     a     b     c    a    b    c
0 None None None None None None 8.00 5.00 2.00
1 None None None 8 5 2 5.00 7.00 7.00
2 8 5 2 5 7 7 3.00 7.00 5.00
3 5 7 7 3 7 5 7.00 7.00 7.00
4 3 7 5 7 7 7 2.00 2.00 6.00
5 7 7 7 2 2 6 nan nan nan
6 2 2 6 NaN NaN NaN nan nan nan
例如第 2 行有 2 个前行。
我用这个代码做到这一点
def laa(df, previous_count):

dfNone = pd.DataFrame({col : None for col in df.columns},
index=[0])
df_tmp = df.copy()
for x in range(1 ,previous_count+1):
df_tmp = pd.concat([dfNone, df_tmp])
df_tmp = df_tmp.reset_index()
del df_tmp['index']
df = pd.concat([df_tmp, df], axis=1)

return df
(必须删除任何行)
Pandas 没有这样做的功能吗?

最佳答案

这将使用 shift() 来解决问题和 concat() Pandas 中的功能:

df = pd.DataFrame(np.random.randint(1,9, size=(5,3)), columns=['a','b','c'])
df1 = pd.concat([df.shift(2), df.shift(1),df], axis = 1)
df2 = pd.concat([df, df.shift(-1),df.shift(-2)], axis = 1)

final_df = pd.concat([df1,df2]).drop_duplicates()
示例输出:
df如下:
+----+-----+-----+-----+
| | a | b | c |
|----+-----+-----+-----|
| 0 | 6 | 2 | 6 |
| 1 | 7 | 2 | 1 |
| 2 | 4 | 4 | 5 |
| 3 | 1 | 1 | 1 |
| 4 | 2 | 2 | 4 |
+----+-----+-----+-----+
然后, final_df将是 :
+----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| | a | b | c | a | b | c | a | b | c |
|----+-----+-----+-----+-----+-----+-----+-----+-----+-----|
| 0 | nan | nan | nan | nan | nan | nan | 6 | 2 | 6 |
| 1 | nan | nan | nan | 6 | 2 | 6 | 7 | 2 | 1 |
| 2 | 6 | 2 | 6 | 7 | 2 | 1 | 4 | 4 | 5 |
| 3 | 7 | 2 | 1 | 4 | 4 | 5 | 1 | 1 | 1 |
| 4 | 4 | 4 | 5 | 1 | 1 | 1 | 2 | 2 | 4 |
| 3 | 1 | 1 | 1 | 2 | 2 | 4 | nan | nan | nan |
| 4 | 2 | 2 | 4 | nan | nan | nan | nan | nan | nan |
+----+-----+-----+-----+-----+-----+-----+-----+-----+-----+

关于python - 是否有一个 Pandas 函数可以将例如前三行连接在一起(就像我有一个长度为三的窗口),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66458705/

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