数据框的分组与平均列

时间:2020-02-19 17:47:24

标签: python pandas dataframe

我真的是python的新手。就在一周前,我开始学习它。我有一个疑问,希望你们能帮助我解决。预先谢谢.. !!

我的数据格式如下。

Date        Product Price   Discount
1/1/2020    A   17,490  30  
1/1/2020    B   34,990  21
1/1/2020    C   20,734  11  
1/2/2020    A   16,884  26  
1/2/2020    B   26,990  40  
1/2/2020    C   17,936  10  
1/3/2020    A   16,670  36  
1/3/2020    B   12,990  13  
1/3/2020    C   30,990  43  

我想将每个日期的折扣列取平均值,只有2列。这还没有解决..:(

Date        AVG_Discount
1/1/2020    x %
1/2/2020    y %
1/3/2020    z %

我尝试做的事情如下。正如我所说,我是Python新手,所以方法可能不正确。.需要指导的人.. TIA

mean_col=df.groupby(df['time'])['discount'].mean()
df=df.set_index(['time'])
df['mean_col']=mean_col
df=df.reset_index()

2 个答案:

答案 0 :(得分:0)

  • df.groupby(df['time'])['discount'].mean()已经返回以time作为索引的系列。
  • 您所需要做的只是在此上使用reset_index函数。
grouped_df = df.groupby(df['time'])['discount'].mean().reset_index()
  • 如Quang Hoang在评论中建议。您还可以将as_index=False传递给groupby。

答案 1 :(得分:0)

显然,您已经从文本文件中读取了DataFrame, 例如CSV,但使用逗号以外的分隔符。

运行df.info(),我认为您得到的结果如下:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 4 columns):
Date        9 non-null object
Product     9 non-null object
Price       9 non-null object
Discount    9 non-null int64
dtypes: int64(1), object(3)

请注意,日期产品价格列属于 object 类型 (实际上是字符串)。这句话在以下情况下尤其重要 Price 列,因为要补偿平均值,您应具有源列 作为数字(不是字符串)。

因此,您首先应将 Date Price 列转换为适当的类型 ( datetime float )。为此,请运行:

df.Date = pd.to_datetime(df.Date)
df.Price = df.Price.str.replace(',', '.').astype(float)

再次运行df.info(),现在结果应为:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 4 columns):
Date        9 non-null datetime64[ns]
Product     9 non-null object
Price       9 non-null float64
Discount    9 non-null int64
dtypes: datetime64[ns](1), float64(1), int64(1), object(1)

现在您可以计算出运行的平均折扣:

df.groupby('Date').Discount.mean()

对于您的数据,我得到了

Date
2020-01-01    20.666667
2020-01-02    25.333333
2020-01-03    30.666667
Name: Discount, dtype: float64

请注意,您的代码示例包含以下错误:

  • groupby 的参数是列名(或列名列表),因此:
      不需要在括号之间的
    • df
    • 您应该输入 Date (而不是 time )(您没有 time 列)。
  • 您的折扣列以资本 D 开头。