【问题标题】:How to create a DataFrame with two subsequent boolean indexes?如何创建具有两个后续布尔索引的 DataFrame?
【发布时间】:2019-08-27 02:45:19
【问题描述】:

我有一个 pandas 数据框,其中包含每周 3 家商店的销售额。我需要过滤最近一年中最近一个月发生的销售额。

我在 DataFrame 中创建了两个额外的列:一个包含年份,另一个包含月份。然后我创建了一个包含最近一年的变量,并使用布尔索引通过该变量过滤了我的原始 DataFrame。然后我想重复这一步:创建一个包含最近一年中最近一个月的变量,并通过过滤最近一个月来创建第二个数据框。但是,当我尝试执行第二步(按最近月份过滤最近年份的 DataFrame)时,我不断收到错误消息。

这是原始的DataFrame:

    week        storeA  storeB  storeC  
0   2014-05-04  2643    8257    3893        
1   2014-05-11  6444    5736    5634        
2   2018-05-18  9646    2552    4253        
3   2018-06-25  5960    10740   8264        
4   2018-06-01  7412    7374    3208        

我可以创建另外两个包含年份和月份的列

df['month'] = pd.DatetimeIndex(df['week']).month 
df['year'] = pd.DatetimeIndex(df['week']).year

在此之后,我的 DataFrame 如下所示:

    week        storeA  storeB  storeC  year  month
0   2014-05-04  2643    8257    3893    2014  05    
1   2014-05-11  6444    5736    5634    2014  05
2   2018-05-18  9646    2552    4253    2018  05
3   2018-06-25  5960    10740   8264    2018  06
4   2018-06-01  7412    7374    3208    2018  06

然后我创建一个包含最大年份的变量并创建一个具有最大年份的新日期框架:

max_year = df['year'].max()
df_last_year = df[df['year']== max_year]

现在我想重复相同的步骤以过滤最大月份。我创建了一个包含最大月份的新变量:

max_month = df_last_year['month'].max()

但是,当我尝试创建一个新的数据框时,就像我对 max_year 所做的那样,我收到以下错误消息:

df_last_month = df[df_last_year['month']==max_month]

/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:8: UserWarning: Boolean Series key will be reindexed to match DataFrame index.

IndexingError:作为索引器提供的不可对齐的布尔系列(布尔系列的索引与索引对象的索引不匹配

【问题讨论】:

  • 打错了,df[df_last_year['month']==max_month] 应该是df_last_year[df_last_year['month']==max_month]

标签: python pandas dataframe indexing


【解决方案1】:

怎么做?

用途:

df_last_year[df_last_year['month']==max_month]

或替代:

df_last_month=df_last_year.where(df_last_year['month']==max_month).dropna()
df_last_month

输出:

week    storeA  storeB  storeC  year    month
3   2018-06-25  5960.0  10740.0 8264.0  2018.0  6.0
4   2018-06-01  7412.0  7374.0  3208.0  2018.0  6.0

为什么会出错?

df['year']== max_year

输出:

0    False
1    False
2     True
3     True
4     True
Name: year, dtype: bool

df_last_year['year']== max_month

输出:

2    False
3    False
4    False
Name: year, dtype: bool

该系列缺少索引 = 0 和索引 = 1 的布尔值,因此无法使用。

【讨论】:

    【解决方案2】:

    代替:df_last_month = df[df_last_year['month']==max_month]

    输入:df_last_month = df_last_year[df_last_year['month']==max_month]

    您基本上是在尝试根据另一个数据框的列值对数据框进行切片。

    或:df_last_month = df[df['month']==max_month],基于您要从中切片的数据框。

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2021-08-24
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2015-08-07
      • 2017-10-29
      • 1970-01-01
      • 2017-08-15
      相关资源
      最近更新 更多