如何使用两个后续的布尔索引创建DataFrame?

时间:2019-08-26 18:27:28

标签: python pandas dataframe indexing

我有一个Pandas DataFrame,包含每周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:布尔系列键将重新索引以匹配DataFrame索引。

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

2 个答案:

答案 0 :(得分:0)

而不是: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],基于您要从中切片的数据帧。

答案 1 :(得分:0)

怎么做?

使用:

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的布尔值,因此无法使用。