将 X 和 Y 数组转换为频率网格

Mig*_*lez 19 python numpy pivot-table matrix pandas

我想将两个数组(x 和 y)转换为频率nxn矩阵(n = 5),指示每个单元格包含的点数。它包括将两个变量重新采样为五个间隔,并计算每个单元格的现有点数。

我曾尝试使用 pandas pivot_table但不知道引用每个轴坐标的方式。X 和 Y 数组是两个因变量,包含 0 到 100 之间的值。

我真的很感激有人的帮助。非常感谢您提前。

这是代码的示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Arrays example. They are always float type and ranging 0-100. (n_size array = 15)
x = 100 * np.random.random(15)
y = 100 * np.random.random(15)

# Df created for trying to pivot and counting values per cell
df = pd.DataFrame({'X':x,'Y':y})

# Plot the example data:
df.plot(x = 'X',y = 'Y', style = 'o')

Run Code Online (Sandbox Code Playgroud)

这就是我所拥有的在此处输入图片说明

这是目标矩阵,保存为 df: 在此处输入图片说明

amz*_*-ex 6

如果您没有明确需要使用pandas(您不需要,如果它只是一个频率矩阵),请考虑使用numpy.histogram2d

# Sample data
x = 100*np.random.random(15)
y = 100*np.random.random(15)
Run Code Online (Sandbox Code Playgroud)

构建您的垃圾箱(因为您的 x 和 y 垃圾箱是相同的,一组就足够了)

bins = np.linspace(0, 100, 5+1)

# bins = array([  0.,  20.,  40.,  60.,  80., 100.])
Run Code Online (Sandbox Code Playgroud)

现在使用直方图函数

binned, binx, biny = np.histogram2d(x, y, bins = [bins, bins])

# To get the result you desire, transpose
objmat = binned.T
Run Code Online (Sandbox Code Playgroud)

注意: x 值沿第一个维度(轴 0)分箱,这在视觉上意味着“垂直”。因此转置。

绘图:

fig, ax = plt.subplots()
ax.grid()
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)

ax.scatter(x, y)
for i in range(objmat.shape[0]):
    for j in range(objmat.shape[1]):
        c = int(objmat[::-1][j,i])
        ax.text((bins[i]+bins[i+1])/2, (bins[j]+bins[j+1])/2, str(c), fontdict={'fontsize' : 16, 'ha' : 'center', 'va' : 'center'})
Run Code Online (Sandbox Code Playgroud)

结果在此处输入图片说明

  • 我选择这个答案是因为在我看来它是最简单的答案,并且允许改变“n”,但所有答案都很棒。谢谢大家! (2认同)

ans*_*sev 6

您可以将GroupBy.size 匹配的组轴用于每个网格的中心。然后你可以Axes.text用来绘制它们

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(20)


max_val = 100
n = 5
len_group = max_val // 5
x = max_val * np.random.random(15)
y = max_val * np.random.random(15)


# Df created for trying to pivot and counting values per cell
df = pd.DataFrame({'X':x,'Y':y})



x_groups = df['X'] // len_group * len_group + len_group / 2
y_groups = df['Y'] // len_group * len_group + len_group / 2

fig, ax= plt.subplots(figsize=(13, 6))

ax.set_ylim(0, max_val)
ax.set_xlim(0, max_val)

df.plot(x = 'X',y = 'Y', style = 'o', ax=ax)
for i, val in df.groupby([x_groups, y_groups]).size().items():
    ax.text(*i, val,fontdict={'fontsize' : 20, 'ha' : 'center',  'va':'center'})
plt.grid()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明