按条件在日期索引上过滤DataFrame

时间:2018-05-18 14:14:55

标签: python pandas date datetime dataframe

我使用frame['date_created'].value_counts().sort_index()

创建了一个包含值的pandas系列
2013-10     1
2014-12     1
2015-02     1
2015-03     1
2015-09     1
2016-02     6
2016-03     1
2017-05     5
2017-07     2
2017-08    13
2017-09    40
2017-10    47
2017-11    40
2017-12    26
2018-01    16

但我希望过滤此系列以获取2017年及以上日期的数据。我该如何过滤这个?

2 个答案:

答案 0 :(得分:2)

nonce切片

直截了当,如果你正在处理字符串索引,那么切片,强制转换和比较:

(...)
#include <cs50.h>
#include <string.h>
(...)

// extract the first two characters of 'hash' (== nonce/salt)
string hash = "14dJperBYV6zU";
char nonceAsArray[2];

for (int i = 0; i < 2; i++)
{
    nonceAsArray[i] = hash[i];
}

string nonce = concatenateCharacters(nonceAsArray, 2);

printf("first hash: %s\n", crypt("myPassword", "14"));
printf("second hash: %s\n", crypt("myPassword", nonce));

// connects characters to strings
string concatenateCharacters(char characters[], int arraySize)
{
    char terminator[1] = {'\0'};
    // create array that can store the password and to which the terminator can be appended (hence +1)
    char bigEnoughArray[arraySize + 1];

    for (int i = 0; i < arraySize; i++)
    {
        bigEnoughArray[i] = characters[i];
    }

    return strcat(bigEnoughArray, terminator);
}

str[...]

v = frame['date_created'].value_counts().sort_index() v_2017 = v[v.index.str[:4].astype(int) >= 2017]

或者,投射到日期时间 -

print(v_2017)

2017-05     5
2017-07     2
2017-08    13
2017-09    40
2017-10    47
2017-11    40
2017-12    26
2018-01    16
Name: 1, dtype: int64

答案 1 :(得分:0)

这是一种方法:

import pandas as pd

df = pd.DataFrame({'date_created': ['2013-10','2014-12',
                                    '2015-02','2015-03',
                                    '2015-09','2016-02',
                                    '2016-03','2017-05',
                                    '2017-07','2017-08',
                                    '2017-09','2017-10',
                                    '2017-11','2017-12',
                                    '2018-01'],
                    'count': [1, 1, 1, 1, 1, 6, 1, 5, 2, 13, 40, 47, 40, 26, 16]})

print(df[df['date_created'].apply(lambda x: int(x.split('-')[0])).gt(2016)])
#    count date_created
#7       5      2017-05
#8       2      2017-07
#9      13      2017-08
#10     40      2017-09
#11     47      2017-10
#12     40      2017-11
#13     26      2017-12
#14     16      2018-01