Pandas基础(二)

# get_option  获取解释器的默认参数值。
import pandas as pd
print (pd.get_option("display.max_rows"))  # 获取显示上限的行数
print (pd.get_option("display.max_columns"))  # 获取显示上限的列数

60
20

# set_option 更改解释器的默认参数值。
import pandas as pd
pd.set_option("display.max_rows",70)
print (pd.get_option("display.max_rows"))

70

# reset_option 解释器的参数重置为默认值。
import pandas as pd
pd.set_option("display.max_columns",40)
print (pd.get_option("display.max_columns"))

40

# describe_option 输出参数的描述信息。
import pandas as pd
pd.describe_option("display.max_rows")

display.max_rows : int
If max_rows is exceeded, switch to truncate view. Depending on
large_repr, objects are either centrally truncated or printed as
a summary view.

'None' value means unlimited. Beware that printing a large number of rows
could cause your rendering environment (the browser, etc.) to crash.

In case python/IPython is running in a terminal and large_repr
equals 'truncate' this can be set to 0 and pandas will auto-detect
the height of the terminal and print a truncated object which fits
the screen height. The IPython notebook, IPython qtconsole, or
IDLE do not run in a terminal and hence it is not possible to do
correct auto-detection.
[default: 60] [currently: 60]

# option_context 临时设置解释器参数,当退出使用的语句块时,恢复为默认值。

import pandas as pd
with pd.option_context("display.max_rows",10):
   print(pd.get_option("display.max_rows"))
print(pd.get_option("display.max_rows"))

10
60

import numpy as np
import pandas as pd
#创建一组数据
data = {'name': ['John', 'Mike', 'Mozla', 'Rose', 'David', 'Marry', 'Wansi', 'Sidy', 'Jack', 'Alic'],
        'age': [20, 32, 29, np.nan, 15, 28, 21, 30, 37, 25],
        'gender': [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
        'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
label = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=label)
print(df)
#对行操作
print(df.loc['a':'d',:]) #等同于df.loc['a':'d']  # loc[] 接受两个参数,并以','分隔。第一个位置表示行,第二个位置表示列。示例如下:

name age gender isMarried
a John 20.0 0 yes
b Mike 32.0 0 yes
c Mozla 29.0 1 no
d Rose NaN 1 yes
e David 15.0 0 no
f Marry 28.0 1 no
g Wansi 21.0 0 no
h Sidy 30.0 0 yes
i Jack 37.0 1 no
j Alic 25.0 1 no
name age gender isMarried
a John 20.0 0 yes
b Mike 32.0 0 yes
c Mozla 29.0 1 no
d Rose NaN 1 yes

import numpy as np
import pandas as pd
#创建一组数据
data = {'name': ['John', 'Mike', 'Mozla', 'Rose', 'David', 'Marry', 'Wansi', 'Sidy', 'Jack', 'Alic'],
        'age': [20, 32, 29, np.nan, 15, 28, 21, 30, 37, 25],
        'gender': [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
        'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
label = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=label)
print("Our DataFrame is")
print(df)

print(df.loc[:,'name'])

Our DataFrame is
name age gender isMarried
a John 20.0 0 yes
b Mike 32.0 0 yes
c Mozla 29.0 1 no
d Rose NaN 1 yes
e David 15.0 0 no
f Marry 28.0 1 no
g Wansi 21.0 0 no
h Sidy 30.0 0 yes
i Jack 37.0 1 no
j Alic 25.0 1 no
a John
b Mike
c Mozla
d Rose
e David
f Marry
g Wansi
h Sidy
i Jack
j Alic
Name: name, dtype: str

df = pd.DataFrame(np.random.randn(8, 4),index = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)

print(df.loc[['a','b','f','h'],['A','C']])

Our DataFrame is
A B C D
a 0.098550 1.368981 -1.871461 0.408566
b -0.444002 -0.552898 0.224499 0.922593
c 0.813043 -0.227735 -1.075579 -1.565950
d 0.424185 -0.460599 -0.688878 -0.947153
e 1.326993 0.387187 -0.123548 1.220853
f -0.121744 -0.325296 -0.199384 -0.276650
g -0.265299 1.640888 0.695328 -1.190948
h 1.247971 -1.200827 0.078988 -0.016853
A C
a 0.098550 -1.871461
b -0.444002 0.224499
f -0.121744 -0.199384
h 1.247971 0.078988

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4, 4),index = ['a','b','c','d'], columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- -------")

#返回一组布尔值
print(df.loc['b']>0)

Our DataFrame is
A B C D
a -0.344297 1.140041 -0.110019 -1.492319
b -1.115534 -1.149413 -1.412119 0.108479
c -0.885698 -1.055796 -0.707775 -0.451696
d -0.761528 -1.219680 -0.280394 0.147024
------- ------- ------- -------
A False
B False
C False
D True
Name: b, dtype: bool

#.iloc[]
# df.iloc[] 只能使用整数索引,不能使用标签索引,通过整数索引切片选择数据时,前闭后开(不包含边界结束值)。同 Python 和 NumPy 一样,它们的索引都是从 0 开始。
#.iloc[] 提供了以下方式来选择数据:
#1) 整数索引
#2) 整数列表
#3) 数值范围

import pandas as pd
import numpy as np
data = {'name': ['John', 'Mike', 'Mozla', 'Rose', 'David', 'Marry', 'Wansi', 'Sidy', 'Jack', 'Alic'],
        'age': [20, 32, 29, np.nan, 15, 28, 21, 30, 37, 25],
        'gender': [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
        'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
label = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=label)
print("Our DataFrame is")
print(df)
print("------- ------- ------- -------")

print(df.iloc[2,])

Our DataFrame is
name age gender isMarried
a John 20.0 0 yes
b Mike 32.0 0 yes
c Mozla 29.0 1 no
d Rose NaN 1 yes
e David 15.0 0 no
f Marry 28.0 1 no
g Wansi 21.0 0 no
h Sidy 30.0 0 yes
i Jack 37.0 1 no
j Alic 25.0 1 no
------- ------- ------- -------
name Mozla
age 29.0
gender 1
isMarried no
Name: c, dtype: object

import pandas as pd
import numpy as np
# np.random.randn(8,4) 的意思是:生成一个 8行 × 4列 的随机数组,数组中的数值服从标准正态分布
df = pd.DataFrame(np.random.randn(8, 4), columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- -------")

print(df.iloc[[1, 3, 5], [1, 3]])
print(df.iloc[1:3, :])
print(df.iloc[:,1:3])

Our DataFrame is
A B C D
0 -0.789999 0.299301 -0.381234 -0.794342
1 -0.517524 -0.926131 0.528046 -0.385867
2 2.046175 -0.206745 1.337022 -0.271785
3 0.485985 0.300612 -0.420160 1.716309
4 2.211424 0.079590 -0.547222 1.820812
5 0.762801 0.875278 0.943271 -0.477871
6 -1.784555 0.732383 -0.358004 -1.096842
7 -1.031876 0.400083 -1.554928 -1.001196
------- ------- ------- -------
B D
1 -0.926131 -0.385867
3 0.300612 1.716309
5 0.875278 -0.477871
A B C D
1 -0.517524 -0.926131 0.528046 -0.385867
2 2.046175 -0.206745 1.337022 -0.271785
B C
0 0.299301 -0.381234
1 -0.926131 0.528046
2 -0.206745 1.337022
3 0.300612 -0.420160
4 0.079590 -0.547222
5 0.875278 0.943271
6 0.732383 -0.358004
7 0.400083 -1.554928

# pct_change() 该函数将每个元素与其前一个元素进行比较,并计算前后数值的百分比变化。 
import pandas as pd
import numpy as np
#Series结构
s = pd.Series([1,2,3,4,5,4])
print (s.pct_change())
#DataFrame
# np.random.randn(5,2) 的意思是:生成一个 8行 × 4列 的随机数组,数组中的数值服从标准正态分布
df = pd.DataFrame(np.random.randn(5, 2))
print("Our DataFrame is")
print(df)
print("------- ------- ------- -------")

print(df.pct_change())

0 NaN
1 1.000000
2 0.500000
3 0.333333
4 0.250000
5 -0.200000
dtype: float64
Our DataFrame is
0 1
0 0.754722 -0.923255
1 0.724816 0.682324
2 0.722615 0.035091
3 0.291550 0.376838
4 0.369028 0.427940
------- ------- ------- -------
0 1
0 NaN NaN
1 -0.039625 -1.739042
2 -0.003037 -0.948571
3 -0.596536 9.738726
4 0.265747 0.135608

import pandas as pd
import numpy as np
#DataFrame
df = pd.DataFrame(np.random.randn(3, 2))
print("Our DataFrame is")
print(df)
print("------- ------- ------- -------")

print(df.pct_change(axis=1))

Our DataFrame is
0 1
0 -1.455521 1.540908
1 0.893799 -2.559288
2 -1.225710 0.076771
------- ------- ------- -------
0 1
0 NaN -2.058665
1 NaN -3.863380
2 NaN -1.062634

# Series 对象提供了一个cov方法用来计算 Series 对象之间的协方差。同时,该方法也会将缺失值(NAN )自动排除。

import pandas as pd
import numpy as np
s1 = pd.Series(np.random.randn(10))
s2 = pd.Series(np.random.randn(10))
print(s1)
print("------- ------- ------- -------")
print(s2)
print("------- ------- ------- -------")
print (s1.cov(s2))

0 -0.590750
1 0.334338
2 0.644780
3 -1.097406
4 -0.483334
5 -0.426003
6 -1.020708
7 -1.478657
8 1.753608
9 -0.854358
dtype: float64
------- ------- ------- -------
0 0.319924
1 -1.246203
2 2.099647
3 0.220208
4 -1.842044
5 1.121932
6 0.617710
7 0.204033
8 0.264984
9 -0.319700
dtype: float64
------- ------- ------- -------
0.13201340988358468

import pandas as pd
import numpy as np
# np.random.randn(10,5) 的意思是:生成一个 10行 × 5列 的随机数组,数组中的数值服从标准正态分布
frame = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
#计算a与b之间的协方差值
print (frame['a'].cov(frame['b']))
#计算所有数列的协方差值
print (frame.cov())

-0.6769599803264115
a b c d e
a 1.437088 -0.676960 0.279839 -1.053745 0.219140
b -0.676960 1.679369 -0.118384 0.106216 -0.245916
c 0.279839 -0.118384 2.263774 -0.860259 -0.561819
d -1.053745 0.106216 -0.860259 2.204644 0.145877
e 0.219140 -0.245916 -0.561819 0.145877 1.001762

# 相关系数(corr)显示任意两个 Series 之间的线性关系。
# Pandas 提供了计算相关性的三种方法,分别是 pearson(default)、spearman() 和 kendall()。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- -------")

print (df['b'].corr(frame['c']))
print (df.corr())

Our DataFrame is
a b c d e
0 0.376757 0.051221 0.774323 -0.868438 1.708333
1 -0.036573 1.547880 -0.607590 -0.766925 -0.102943
2 -1.633160 -1.568195 0.079952 1.301703 0.423066
3 1.680652 1.091357 -2.471378 0.486649 -1.249641
4 -0.635293 -0.252618 0.450307 -2.651562 2.118488
5 -0.889529 1.475028 -0.747123 -0.725263 0.967182
6 1.345565 1.941289 0.208636 -0.676611 0.362650
7 -1.386417 -0.561730 -0.374336 0.508931 0.531593
8 -0.441762 1.128805 1.690708 -1.636528 0.559627
9 -0.959460 -1.108624 -1.705281 -2.498656 -0.067572
------- ------- ------- -------
-0.261126923181585
a b c d e
a 1.000000 0.667253 -0.216720 0.022361 -0.363574
b 0.667253 1.000000 0.036693 -0.070812 -0.197748
c -0.216720 0.036693 1.000000 -0.203389 0.691151
d 0.022361 -0.070812 -0.203389 1.000000 -0.416393
e -0.363574 -0.197748 0.691151 -0.416393 1.000000

#排名(rank)
#rank() 按照某种规则(升序或者降序)对序列中的元素值排名,该函数的返回值的也是一个序列,包含了原序列中每个元素值的名次。
# 如果序列中包含两个相同的的元素值,那么会为其分配两者的平均排名。示例如下:

import pandas as pd
import numpy as np
#返回5个随机值,然后使用rank对其排名
s = pd.Series(np.random.randn(5), index=list('abcde'))
s['d'] = s['b']
print("Our Series is")
print(s)
print("------- ------- ------- -------")
#a/b排名分别为2和3,其平均排名为2.5
print(s.rank())

Our Series is
a -0.630581
b 0.108192
c 1.030878
d 0.108192
e -0.655648
dtype: float64
------- ------- ------- -------
a 2.0
b 3.5
c 5.0
d 3.5
e 1.0
dtype: float64

# rank() 提供了 method 参数,可以针对相同数据,进行不同方式的排名
# average:默认值,如果数据相同则分配平均排名;
# min:给相同数据分配最低排名;
# max:给相同数据分配最大排名;
# first:对于相同数据,根据出现在数组中的顺序进行排名。
# rank() 有一个ascening参数, 默认为 True 代表升序;如果为 False,则表示降序排名(将较大的数值分配给较小的排名)。
# rank() 默认按行方向排名(axis=0),也可以更改为 axis =1

import pandas as pd
import numpy as np
a = pd.DataFrame(np.arange(12).reshape(3,4),columns = list("abdc"))
print("Our DataFrame is")
print(a)
print("------- ------- ------- -------")

a =a.sort_index(axis=1,ascending=False)
print(a)
print("------- ------- ------- -------")
a.iloc[[1,1],[1,2]] = 6
#按行排名,将相同数值设置为所在行数值的最大排名
print(a.rank(axis=1,method="max"))

Our DataFrame is
a b d c
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
------- ------- ------- -------
d c b a
0 2 3 1 0
1 6 7 5 4
2 10 11 9 8
------- ------- ------- -------
d c b a
0 3.0 4.0 2.0 1.0
1 4.0 4.0 4.0 1.0
2 3.0 4.0 2.0 1.0

# window 默认值为 1,表示窗口的大小,也就是观测值的数量,
# min_periods 表示窗口的最小观察值,默认与 window 的参数值相等。
# center 是否把中间值做为窗口标准,默认值为 False。

# 窗口函数 举一个简单的例子:现在有 10 天的销售额,而您想每 3 天求一次销售总和,
# 也就说第五天的销售额等于(第三天 + 第四天 + 第五天)的销售额之和,此时窗口函数就派上用场了

import pandas as pd
import numpy as np
#生成时间序列
df = pd.DataFrame(np.random.randn(8, 4),index = pd.date_range('12/1/2026', periods=8),columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- -------")

#每3个数求求一次均值
print(df.rolling(window=3).mean())  # 表示是每一列中依次紧邻的每 3 个数求一次均值。当不满足 3 个数时,所求值均为 NaN 值,因此前两列的值为 NaN,直到第三行值才满足要求 window =3

Our DataFrame is
A B C D
2026-12-01 2.268955 1.020684 1.449977 -0.749461
2026-12-02 0.679106 1.061078 0.164973 0.385570
2026-12-03 -1.652965 -0.131055 0.345697 2.016105
2026-12-04 -0.672328 -0.267566 -0.729921 -0.922642
2026-12-05 0.824588 -0.149531 0.747187 1.034033
2026-12-06 -0.866715 0.436809 0.067569 -0.710707
2026-12-07 1.531011 1.018981 0.820498 0.963756
2026-12-08 0.347458 1.405321 -0.614540 -0.987205
------- ------- ------- -------
A B C D
2026-12-01 NaN NaN NaN NaN
2026-12-02 NaN NaN NaN NaN
2026-12-03 0.431699 0.650236 0.653549 0.550738
2026-12-04 -0.548729 0.220819 -0.073084 0.493011
2026-12-05 -0.500235 -0.182718 0.120988 0.709165
2026-12-06 -0.238152 0.006570 0.028278 -0.199772
2026-12-07 0.496295 0.435420 0.545085 0.429027
2026-12-08 0.337251 0.953704 0.091176 -0.244719

# expanding() 又叫扩展窗口函数,扩展是指由序列的第一个元素开始,逐个向后计算元素的聚合值。

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
      index = pd.date_range('1/1/2026', periods=10),
      columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- ------- ------- -------")

print (df.expanding(min_periods=3).mean())

Our DataFrame is
A B C D
2026-01-01 -0.367239 0.811207 -0.424291 1.645512
2026-01-02 -1.586289 -1.099992 -1.904203 -1.065463
2026-01-03 -0.998680 1.543207 0.170001 -0.332421
2026-01-04 0.250463 1.367449 -0.895217 0.483651
2026-01-05 -1.225360 0.012229 -0.392580 0.440516
2026-01-06 0.135193 -0.579399 -0.293987 -0.629547
2026-01-07 -0.122366 -1.761879 0.849887 0.433837
2026-01-08 -0.191763 0.051392 -1.616432 -0.490857
2026-01-09 -0.531074 -0.958319 1.201396 0.312768
2026-01-10 0.198474 -0.849736 1.213209 -0.198457
------- ------- ------- ------- ------- -------
A B C D
2026-01-01 NaN NaN NaN NaN
2026-01-02 NaN NaN NaN NaN
2026-01-03 -0.984069 0.418141 -0.719498 0.082542
2026-01-04 -0.675436 0.655468 -0.763428 0.182820
2026-01-05 -0.785421 0.526820 -0.689258 0.234359
2026-01-06 -0.631985 0.342450 -0.623379 0.090375
2026-01-07 -0.559183 0.041832 -0.412913 0.139441
2026-01-08 -0.513255 0.043027 -0.563353 0.060654
2026-01-09 -0.515235 -0.068234 -0.367270 0.088666
2026-01-10 -0.443864 -0.146384 -0.209222 0.059954

# expanding() 又叫扩展窗口函数,扩展是指由序列的第一个元素开始,逐个向后计算元素的聚合值。
# 下面示例,min_periods = n表示向后移动 n 个值计求一次平均值:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
      index = pd.date_range('1/1/2026', periods=10),
      columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- ------- ------- -------")
print (df.expanding(min_periods=3).mean())

Our DataFrame is
A B C D
2026-01-01 1.218309 1.503762 -0.624062 1.158656
2026-01-02 0.071820 -0.512625 -1.136965 0.173278
2026-01-03 -0.670813 0.642414 -1.153807 -0.191632
2026-01-04 -0.385152 -1.267221 0.663206 0.009837
2026-01-05 0.122569 -0.992959 0.756212 -1.574027
2026-01-06 0.489731 -0.805899 -1.345997 1.699809
2026-01-07 1.036641 -1.576341 0.879409 -0.351036
2026-01-08 -0.811148 0.612757 0.381163 -0.169197
2026-01-09 -0.164836 -0.564826 2.881346 -0.271357
2026-01-10 0.712461 -0.442730 0.280042 0.867105
------- ------- ------- ------- ------- -------
A B C D
2026-01-01 NaN NaN NaN NaN
2026-01-02 NaN NaN NaN NaN
2026-01-03 0.206439 0.544517 -0.971611 0.380101
2026-01-04 0.058541 0.091583 -0.562907 0.287535
2026-01-05 0.071347 -0.125326 -0.299083 -0.084778
2026-01-06 0.141077 -0.238755 -0.473569 0.212653
2026-01-07 0.269015 -0.429838 -0.280286 0.132126
2026-01-08 0.133995 -0.299514 -0.197605 0.094461
2026-01-09 0.100791 -0.328993 0.144500 0.053815
2026-01-10 0.161958 -0.340367 0.158055 0.135144

# ewm(全称 Exponentially Weighted Moving)表示指数加权移动。
# ewn() 函数先会对序列元素做指数加权运算,其次计算加权后的均值。该函数通过指定 com、span 或者 halflife 参数来实现指数加权移动。
# 在数据分析的过程中,使用窗口函数能够提升数据的准确性,并且使数据曲线的变化趋势更加平滑,从而让数据分析变得更加准确、可靠
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
   index = pd.date_range('04/1/2026', periods=10),
   columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- ------- ------- -------")
#设置com=0.5,先加权再求均值
print(df.ewm(com=0.5).mean())

Our DataFrame is
A B C D
2026-04-01 -1.027250 0.299016 1.653497 0.444546
2026-04-02 -0.156717 -0.088606 -1.131506 0.316332
2026-04-03 1.120565 -0.860011 -0.039464 -0.828569
2026-04-04 -0.944554 1.499255 0.134146 -0.550440
2026-04-05 -1.113271 0.598478 1.168219 -0.392384
2026-04-06 0.298092 -0.926458 -0.696845 -0.848041
2026-04-07 0.643020 -1.059591 -0.599818 0.235301
2026-04-08 -0.468213 0.033976 -1.322941 0.812954
2026-04-09 -1.011467 0.265918 -0.242015 -0.343889
2026-04-10 -1.173833 -0.120190 -0.507569 -0.209733
------- ------- ------- ------- ------- -------
A B C D
2026-04-01 -1.027250 0.299016 1.653497 0.444546
2026-04-02 -0.374351 0.008299 -0.435255 0.348385
2026-04-03 0.660591 -0.592839 -0.161246 -0.466429
2026-04-04 -0.422882 0.819325 0.038143 -0.523137
2026-04-05 -0.885043 0.671485 0.794640 -0.435608
2026-04-06 -0.095203 -0.395273 -0.201049 -0.710941
2026-04-07 0.397171 -0.838355 -0.467016 -0.079825
2026-04-08 -0.179839 -0.256712 -1.037720 0.515452
2026-04-09 -0.734286 0.091726 -0.507223 -0.057471
2026-04-10 -1.027322 -0.049554 -0.507454 -0.158981

import pandas as pd
import numpy as np
# np.random.randn(5,4) 的意思是:生成一个 5行 × 4列 的随机数组,数组中的数值服从标准正态分布
df = pd.DataFrame(np.random.randn(5, 4),index = pd.date_range('04/14/2026', periods=5),columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- ------- ------- -------")
#窗口大小为3,min_periods 最小观测值为1
r = df.rolling(window=3,min_periods=1) 
#1. window=3
#窗口大小为3,即每次计算时包含当前行及前面2行(共3行数据)
#类似于一个长度为3的滑动窗口

# min_periods=1
# 窗口中最少需要的有效观测值数量
# 即使窗口内不足3个数据,只要有至少1个非空值就进行计算
# 特别适用于数据序列的开始部分
print(r) 

# 1. 计算滚动均值(平滑数据)
rolling_mean = df.rolling(window=3, min_periods=1).mean()
print(rolling_mean) 
print("------- ------- ------- ------- ------- -------")
# 2. 计算滚动总和
rolling_sum = df.rolling(window=3, min_periods=1).sum()
print(rolling_sum) 
print("------- ------- ------- ------- ------- -------")
# 3. 计算滚动标准差
rolling_std = df.rolling(window=3, min_periods=1).std()
print(rolling_std) 
print("------- ------- ------- ------- ------- -------")
# 4. 计算滚动最大值
rolling_max = df.rolling(window=3, min_periods=1).max()
print(rolling_max) 
print("------- ------- ------- ------- ------- -------")

Our DataFrame is
A B C D
2026-04-14 -1.118517 -0.242172 0.986486 -0.500875
2026-04-15 -0.087599 -1.791542 0.667961 -0.880049
2026-04-16 1.049823 -0.421797 -0.759785 -0.353671
2026-04-17 0.266416 -1.856131 0.510709 -0.420604
2026-04-18 -0.316200 0.672917 -1.258313 0.138747
------- ------- ------- ------- ------- -------
Rolling [window=3,min_periods=1,center=False,method=single]
A B C D
2026-04-14 -1.118517 -0.242172 0.986486 -0.500875
2026-04-15 -0.603058 -1.016857 0.827223 -0.690462
2026-04-16 -0.052098 -0.818503 0.298221 -0.578198
2026-04-17 0.409547 -1.356490 0.139628 -0.551441
2026-04-18 0.333346 -0.535003 -0.502463 -0.211843
------- ------- ------- ------- ------- -------
A B C D
2026-04-14 -1.118517 -0.242172 0.986486 -0.500875
2026-04-15 -1.206116 -2.033714 1.654447 -1.380923
2026-04-16 -0.156293 -2.455510 0.894662 -1.734594
2026-04-17 1.228640 -4.069470 0.418885 -1.654324
2026-04-18 1.000039 -1.605010 -1.507389 -0.635529
------- ------- ------- ------- ------- -------
A B C D
2026-04-14 NaN NaN NaN NaN
2026-04-15 0.728969 1.095571 0.225232 0.268116
2026-04-16 1.084606 0.847449 0.929998 0.271574
2026-04-17 0.582062 0.810112 0.782873 0.286543
2026-04-18 0.685466 1.268319 0.912152 0.305458
------- ------- ------- ------- ------- -------
A B C D
2026-04-14 -1.118517 -0.242172 0.986486 -0.500875
2026-04-15 -0.087599 -0.242172 0.986486 -0.500875
2026-04-16 1.049823 -0.242172 0.986486 -0.353671
2026-04-17 1.049823 -0.421797 0.667961 -0.353671
2026-04-18 1.049823 0.672917 0.510709 0.138747
------- ------- ------- ------- ------- -------

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 4),index = pd.date_range('14/04/2026', periods=5),columns = ['A', 'B', 'C', 'D'])
print("Our DataFrame is")
print(df)
print("------- ------- ------- ------- ------- -------")
#窗口大小为3,min_periods 最小观测值为1
r = df.rolling(window=3,min_periods=1)
#使用 aggregate()聚合操作
print(r.aggregate(np.sum))

Our DataFrame is
A B C D
2026-04-14 -1.307740 -1.541177 -1.012944 -0.707454
2026-04-15 0.553605 0.245483 -0.016074 -0.551640
2026-04-16 -1.127926 1.244124 0.614891 0.203014
2026-04-17 -1.748636 -1.080350 -0.570399 1.861618
2026-04-18 0.247527 -0.861632 -0.486765 -0.790101
------- ------- ------- ------- ------- -------
A B C D
2026-04-14 -1.307740 -1.541177 -1.012944 -0.707454
2026-04-15 -0.754135 -1.295694 -1.029018 -1.259094
2026-04-16 -1.882060 -0.051569 -0.414127 -1.056080
2026-04-17 -2.322957 0.409257 0.028417 1.512992
2026-04-18 -2.629035 -0.697859 -0.442274 1.274531

posted @ 2026-04-15 19:42  是17阿哥呀  阅读(6)  评论(0)    收藏  举报