Python 如何使用groupby将值附加到列表?

Python 如何使用groupby将值附加到列表?,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有两个问题 第一: 如何将“价格”列的值附加到列表中?对下面的代码应用to_list方法只会将平均折扣附加到列表中,但我还需要将第一列(价格)单独提取到列表中 df = pd.read_json(prices.json, orient = "records") df.groupby("Prices")["Discounts"].mean() Prices 421.0 93.243137 415.0 91.8

我有两个问题

第一:

如何将“价格”列的值附加到列表中?对下面的代码应用
to_list
方法只会将平均折扣附加到列表中,但我还需要将第一列(价格)单独提取到列表中

df = pd.read_json(prices.json, orient = "records")    
df.groupby("Prices")["Discounts"].mean()


Prices
421.0     93.243137
415.0     91.830721
147.0     96.098335
451.0     98.308000
532.0     99.589286
             ...
1333.0    91.655944
7124.0    94.670829
1315.0    97.975439
6316.0    91.800000
1334.0    99.081081

第二:

在将值添加到列表中时,如何将平均折扣数(第二列)四舍五入到最接近的100?

是这样的

prices_column = []
discounts_column = []

discounts_column.extend(df.groupby("Prices")["Discounts"].mean().to_list())

结果

df = pd.DataFrame({'A': [1, 1, 2, 1],
                   'B': [1010.1112, 1300.009, 749.78, 900.98]})

df_dict = df.groupby('A')['B'].mean().round(2).to_dict()
a_column = list(df_dict.keys())
b_column = list(df_dict.values())

您要查找的内容?

a\u列生成所需的输出,但b\u列在我的例子中只打印100。@Alexander,这可能是因为距离平均值最近的100是100(对于示例值,情况确实如此)。也许我误解了你所说的“最接近的100”的意思?例如,1005678应该是100,57。@Alexander我明白了。我已经更新了我的答案。
[1, 2]
[1070.37, 749.78]