Numpy或Pandas函数用于;“x值窗口”;意味着什么或其他统计数据?
假设我有x-y数据样本,按x值排序。我将以Pandas为例,但我当然非常乐意使用仅限Numpy/Scipy的解决方案Numpy或Pandas函数用于;“x值窗口”;意味着什么或其他统计数据?,numpy,pandas,Numpy,Pandas,假设我有x-y数据样本,按x值排序。我将以Pandas为例,但我当然非常乐意使用仅限Numpy/Scipy的解决方案 In [24]: pd.set_option('display.max_rows', 10) In [25]: df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y']) In [26]: df = df.sort('x') In [27]: df Out[27]: x y 1
In [24]: pd.set_option('display.max_rows', 10)
In [25]: df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y'])
In [26]: df = df.sort('x')
In [27]: df
Out[27]:
x y
13 -3.403818 0.717744
49 -2.688876 1.936267
74 -2.388332 -0.121599
52 -2.185848 0.617896
90 -2.155343 -1.132673
.. ... ...
65 1.736506 -0.170502
0 1.770901 0.520490
60 1.878376 0.206113
63 2.263602 1.112115
33 2.384195 -1.877502
[100 rows x 2 columns]
现在,我想对它进行“窗口化”或“离散化”,并获得每个窗口的统计数据。但我不想做熊猫,因为它们按行定义窗口。我想用x值的范围来定义窗口,因此是“x值窗口”。具体来说,让我们用两个参数定义每个x值窗口:
- 在这个例子中,假设我想要x=0.0+0.4*k表示所有的正k或负k
- 因此-3.2,-2.8,-2.4,…,1.6,2.0,2.4
- 在这个例子中,假设我想要W=0.5
- 因此,示例窗口将是[-3.2-0.25,-3.2+0.25],-2.8-0.25,-2.8+0.25],…,[2.4-0.25,2.4+0.25]
- 请注意,窗口重叠,这是预期的
Extra 2:如果x值窗口上支持除平均值以外的统计数据,那就太好了,例如:(a)每个x值窗口中y值的方差,或(b)每个x值窗口内的样本数计数。我首先创建一个以零为中心的x值范围。该范围足够宽,因此最小值减去宽度,最大值加上宽度将捕获所有x值 然后,我遍历以
k
作为步长的x值范围。在每个点上,我使用loc
捕获位于所选x
值加上和减去宽度的y
值。然后计算这些选定值的平均值。这些值用于创建结果
数据帧
import math
import numpy as np
import pandas as pd
k = .4
w = .5
np.random.seed(0)
df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y'])
x_range = np.arange(math.floor((df.x.min() + w) / k) * k,
k * (math.ceil((df.x.max() - w) / k) + 1), k)
result = pd.DataFrame((df.loc[df.x.between(x - w, x + w), 'y'].mean() for x in x_range),
index=x_range, columns=['y_mean'])
result.index.name = 'centered_x'
>>> result
y_mean
centered_x
-2.400000e+00 0.653619
-2.000000e+00 0.733606
-1.600000e+00 0.576594
-1.200000e+00 0.150462
-8.000000e-01 0.065884
-4.000000e-01 0.022925
-8.881784e-16 0.211693
4.000000e-01 0.057527
8.000000e-01 -0.141970
1.200000e+00 0.233695
1.600000e+00 0.203570
2.000000e+00 0.306409
2.400000e+00 0.576789
谢谢你的回答!这似乎更接近于“滚动我自己的”而不是“支持的功能”。这并不是我想要的答案(我可以滚动我自己的代码,而无需帮助编写代码),但我给予了赞扬,因为你是唯一花时间编写答案的人。
import math
import numpy as np
import pandas as pd
k = .4
w = .5
np.random.seed(0)
df = pd.DataFrame(np.random.randn(100, 2), columns=['x', 'y'])
x_range = np.arange(math.floor((df.x.min() + w) / k) * k,
k * (math.ceil((df.x.max() - w) / k) + 1), k)
result = pd.DataFrame((df.loc[df.x.between(x - w, x + w), 'y'].mean() for x in x_range),
index=x_range, columns=['y_mean'])
result.index.name = 'centered_x'
>>> result
y_mean
centered_x
-2.400000e+00 0.653619
-2.000000e+00 0.733606
-1.600000e+00 0.576594
-1.200000e+00 0.150462
-8.000000e-01 0.065884
-4.000000e-01 0.022925
-8.881784e-16 0.211693
4.000000e-01 0.057527
8.000000e-01 -0.141970
1.200000e+00 0.233695
1.600000e+00 0.203570
2.000000e+00 0.306409
2.400000e+00 0.576789