【发布时间】:2020-11-09 15:18:23
【问题描述】:
我有一个大小为 700x20 的数据框。我的数据是图像上特定位置的像素强度坐标,我有 14 个人,每个人有 50 张图像。我正在尝试执行降维,对于这样的任务,其中一个步骤需要我计算每个类之间的平均值,其中我有两个类。在我的数据框中,每 50 行是属于一个类的特征,因此 A 类有 0 到 50 个特征,B 类有 51 到 100 个特征,A 类有 101-150 个,类有 151-200 个B 等等。
我想要做的是计算每个给定行的平均值,从 N 到 M 并计算平均值。这是数据框的链接,以便更好地可视化问题:Dataframe pickle file
我尝试的是对数据框进行排序并单独计算,但它不起作用,它计算了每一行的平均值并将它们分组为 14 个不同的类。
class_feature_means = pd.DataFrame(columns=target_names)
for c, rows in df.groupby('class'):
class_feature_means[c] = rows.mean()
class_feature_means
最小的可重现示例:
my_array = np.asarray([[31, 25, 17, 62],
[31, 26, 19, 59,],
[31, 23, 17, 67,],
[31, 23, 19, 67,],
[31, 28, 17, 65,],
[32, 26, 19, 62,],
[32, 26, 17, 66,],
[30, 24, 17, 68],
[29, 24, 17, 68],
[33, 24, 17, 68],
[32, 52, 16, 68],
[29, 24, 17, 68],
[33, 24, 17, 68],
[32, 52, 16, 68],
[29, 24, 17, 68],
[33, 24, 17, 68],
[32, 52, 16, 68],
[30, 25, 16, 97]])
my_array = my_array.reshape(18, 4)
my_array = my_array.reshape(18, 4)
indices = sorted(list(range(0,int(my_array.shape[0]/3)))*3)
class_dict = dict(zip(range(0,int((my_array.shape[0]/3))), string.ascii_uppercase))
target_names = ["Index_" + c for c in class_dict.values()]
pixel_index = [1, 2, 3, 4]
X = pd.DataFrame(my_array, columns= pixel_index)
y = pd.Categorical.from_codes(indices,target_names)
df = X.join(pd.Series(y,name='class'))
df
基本上我想要做的是分组为一个独特的类 A、C、E,将它们的总和除以 3,从而实现 A 类的平均值或将其称为 0 类。 然后,分组为一个唯一的类 B、D、F,将它们的和除以 3,从而获得 B 类或 1 类的平均值。
【问题讨论】:
标签: python arrays python-3.x numpy dataframe