有没有办法使用Pandas删除行,更改文件,删除下一​​行,更改文件等等?

时间:2019-06-13 17:36:03

标签: python pandas

所以这在问题的疯狂方面有点,所以我提前道歉。...我要实现的功能是能够从CSV文件中读取最早的日期,并将其与今天的日期进行比较,如果两者之差等于或大于55,它将使用Pandas删除行,直到满足条件为止。

我通过使用df.drop()尝试了几种不同的方法,但是,我得到的最接近的代码如下。

此外,这也是我正在使用的testFile.csv中的数字。 (CSV文件中的所有内容都是由字符串组成的)

2019-05-01 | 14

2019-05-02 | 16

2019-05-03 | 2

2019-05-04 | 3

2019-05-05 | 3

2019-05-06 | 6

2019-05-07 | 14

2019-05-08 | 8

2019-05-09 | 5

2019-05-10 | 1

2019-05-11 | 5

2019-05-12 | 4

2019-05-13 | 1

2019-05-14 | 2

2019-05-15 | 3

2019-05-16 | 8

2019-05-17 | 2

2019-05-18 | 3

2019-05-19 | 4

2019-05-20 | 4
import datetime, time
import pandas as pd
GLOBAL_PATH = r'C:\Users\DArthur\Documents'
pattern = '%Y-%m-%d'  # CSV Pattern
el_pattern = '%m/%d/%Y:00:00:00'  # Required Pattern by Splunk for search_query, used for TimeStamp


def remove_old_data(csv_file):
    df = pd.read_csv(GLOBAL_PATH + csv_file, sep=',', index_col=0, encoding='utf-8', low_memory=False)
    s = pd.Series(pd.to_datetime('today') - pd.to_datetime(df.index[0])).dt.days  # Calculate the date difference
    print(s[0], type(s[0]), type(s))  # Result -- 57 <class 'numpy.int64'> <class 'pandas.core.series.Series'>
    df[s.le(55)]#.reset_index(drop=True).to_csv(csv_file, index=False)
    print(df)


if __name__ == '__main__':
    # get_last_date('/testFile.csv')
    remove_old_data('/testFile.csv')

由于CSV文件的最早日期是从今天开始的57天,因此应从文件中删除前两行。因此,在程序运行后打开文件时,其第一行从2019-05-03开始| 2。

非常感谢您提供的任何帮助或指向正确的方向。 :)

1 个答案:

答案 0 :(得分:1)

IIUC,使用:

s=(pd.to_datetime('today')-pd.to_datetime(df.date)).dt.days
df[s.le(40)]#.reset_index(drop=True).to_csv(file,index=False)

          date  count
3   2019-05-04       3
4   2019-05-05       3
5   2019-05-06       6
6   2019-05-07      14
7   2019-05-08       8
8   2019-05-09       5
9   2019-05-10       1
10  2019-05-11       5
11  2019-05-12       4
12  2019-05-13       1
13  2019-05-14       2
14  2019-05-15       3
15  2019-05-16       8
16  2019-05-17       2
17  2019-05-18       3
18  2019-05-19       4
19  2019-05-20       4