簡體   English   中英

通過列中特定月份的日期來划分熊貓數據框?

[英]Subset pandas dataframe by particular months of dates in column?

如何子集熊貓數據框以獲取包含特定月份數據的行?

我有一個2010-01-01格式的日期列。

如果被索引,我會用

df.ix[date1:date2]

但是,如果數據在列中怎么辦?

可以使用遮罩在DataFrames中選擇范圍。

遮罩只是包含TrueFalse元素的普通pd.Series

使用奴才的一般示例:

df_minions = pd.DataFrame({
    'color':['Red', 'Green', 'Blue', 'Brown'] * 2,
    'name':['Burnie', 'Stinky', 'Swimmy', 'Bashy', 'Flamie', 'Stabbie', 'Blubb', 'Smashie']})
   color     name
0    Red   Burnie
1  Green   Stinky
2   Blue   Swimmy
3  Brown    Bashy
4    Red   Flamie
5  Green  Stabbie
6   Blue    Blubb
7  Brown  Smashie

可以很容易地選擇所有棕色的爪牙:

brown_minion_mask = df_minions['color'] == 'Brown'
0    False
1    False
2    False
3     True
4    False
5    False
6    False
7     True

df_minions[brown_minion_mask]
   color     name
3  Brown    Bashy
7  Brown  Smashie

現在,對於您有關選擇日期月份的具體問題:

首先,我將添加一個充滿日期的spawned

df_minions['spawned'] = [datetime(2015, m, 5) for m in range(4,6)] * 4
   color     name    spawned
0    Red   Burnie 2015-04-05
1  Green   Stinky 2015-05-05
2   Blue   Swimmy 2015-04-05
3  Brown    Bashy 2015-05-05
4    Red   Flamie 2015-04-05
5  Green  Stabbie 2015-05-05
6   Blue    Blubb 2015-04-05
7  Brown  Smashie 2015-05-05

現在,我們可以正確訪問非常特殊的pd.TimeSeries ,即.dt訪問器。

df_minions.spawned.dt.month
0    4
1    5
2    4
3    5
4    4
5    5
6    4
7    5

我們可以使用此操作來掩蓋我們的數據框,就像處理小兵的顏色一樣。

may_minion_mask = df_minions.spawned.dt.month == 5
df_minions[may_minion_mask]
   color     name    spawned
1  Green   Stinky 2015-05-05
3  Brown    Bashy 2015-05-05
5  Green  Stabbie 2015-05-05
7  Brown  Smashie 2015-05-05

您當然可以在面具中進行任何類型的操作

not_spawned_in_january = df_minions.spawned.dt.month != 1
summer_minions = ((df_minions.spawned > datetime(2015,5,15)) &
                  (df_minions.spawned < datetime(2015,9,15))
name_endswith_y = df_minions.name.str.endswith('y')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM