gpt4 book ai didi

python - 有没有办法使用 Pandas 删除一行、更改文件、删除下一行、更改文件等等?

转载 作者:行者123 更新时间:2023-12-01 07:43:15 24 4
gpt4 key购买 nike

所以这有点疯狂,所以我提前道歉......我想要完成的是能够从 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.

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

最佳答案

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

关于python - 有没有办法使用 Pandas 删除一行、更改文件、删除下一行、更改文件等等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com