根据特定行获取 pandas 中列的平均值

Get average of columns in pandas based on particular rows

我有一个数据,用于存储一天、一个月、三个月和一年内股票价值的百分比变化。

ID     daychange   monthchange   trimonthchange  yearchange
UNITY   0.001666     0.398450        0.411581    0.689139
SSOM  -0.033359     0.040816        1.174840    3.047619
PNSC  -0.004953    -0.053006        0.158677    0.224932
PICT  -0.002027    -0.069696        0.041143    0.310791
PIBTL  -0.014848     0.129362        0.459846    0.287100

我想得到:

  1. 基于 ID 名称的 4 个时间段中每个时间段的平均值。例如,“UNITY”、“SSOM”、“PNSC”将被分组,并计算每个时间段的平均值(即该组的平均日变化、该组的平均月变化等)。
  2. 将平均数据放入单独的 csv 文件中,其中包含一个新的单行(而不是“UNITY”、“SSOM”、“PNSC”)以及该组每个时间段的平均值。

我试过 df.mean(axis = 1) 但还是不行。

非常感谢任何帮助!谢谢

您可能需要链接 filtermean 函数调用。由于您首先要 select 保留一组行,因此您需要过滤掉不需要的行。然后,对于新数据集,您要执行列平均。

df.filter(lambda row: row.ID in ["UNITY", "SSOM", "PNSC"]).mean(axis = 1)

注意,我没有测试过上面的代码,不保证它会工作as-is

使用loc to access a group of rows by label (ID column) and then calculate the mean for each time period column using axis=0. Create a Series with the group's name and append the previous results to it (this way the group name will be the first column in the dataframe). Place the Series in a list, then when the iteration over the groups is done, convert to a dataframe. To put the resulst in a separate csv file use to_csv.

import pandas as pd

GROUPS = [
    ["UNITY", "SSOM", "PNSC"],
    ["SSOM", "PICT", "PIBTL"],
    ["SSOM", "PNSC", "PIBTL"],
]

df = pd.read_csv("sample.csv", sep="\s+")
df = df.set_index("ID")

data = []
for g in GROUPS:
    group_mean = df.loc[g].mean(axis=0)
    serie = pd.Series({"groupName":"-".join(g)}).append(group_mean)
    data.append(serie)

data = pd.DataFrame(data)
print(data)
data.to_csv("output.csv", index=False)

来自数据的输出

         groupName  daychange  monthchange  trimonthchange  yearchange
0  UNITY-SSOM-PNSC  -0.012215     0.128753        0.581699    1.320563
1  SSOM-PICT-PIBTL  -0.016745     0.033494        0.558610    1.215170
2  SSOM-PNSC-PIBTL  -0.017720     0.039057        0.597788    1.186550