gpt4 book ai didi

python - 读取csv文件时如何以时间升序方式获取最近一天的行?

转载 作者:行者123 更新时间:2023-12-01 07:48:19 25 4
gpt4 key购买 nike

我想获取最近一天的行,按时间升序排列。
我得到的数据框如下:

    label      uId          adId    operTime                    siteId  slotId  contentId   netType
0 0 u147333631 3887 2019-03-30 15:01:55.617 10 30 2137 1
1 0 u146930169 1462 2019-03-31 09:51:15.275 3 32 1373 1
2 0 u139816523 2084 2019-03-27 08:10:41.769 10 30 2336 1
3 0 u106546472 1460 2019-03-31 08:51:41.085 3 32 1371 4
4 0 u106642861 2295 2019-03-27 22:58:03.679 3 32 2567 4

因为我在这个 csv 文件中获得了大约 1 亿行,所以不可能将所有这些加载到我的电脑内存中。
因此,我想在读取此 csv 文件时以时间升序方式获取最近一天的行。
例如,如果最近一天是2019-04-04,则输出如下:

#this not a real data, just for examples.
label uId adId operTime siteId slotId contentId netType
0 0 u147336431 3887 2019-04-04 00:08:42.315 1 54 2427 2
1 0 u146933269 1462 2019-04-04 01:06:16.417 30 36 1343 6
2 0 u139536523 2084 2019-04-04 02:08:58.079 15 23 1536 7
3 0 u106663472 1460 2019-04-04 03:21:13.050 32 45 1352 2
4 0 u121642861 2295 2019-04-04 04:36:08.653 3 33 3267 4

有人可以帮助我吗?
提前致谢。

最佳答案

我假设您无法将整个文件读入内存,并且该文件是随机顺序的。您可以分块读取文件并迭代这些 block 。

# read 50,000 lines of the file at a time
reader = pd.read_csv(
'csv_file.csv',
parse_dates=True,
chunksize=5e5,
header=0
)

recent_day=pd.datetime(2019,4,4)
next_day=recent_day + pd.Timedelta(days=1)
df_list=[]

for chunk in reader:
#check if any rows match the date range
date_rows = chunk.loc[
(chunk['operTime'] >= recent_day]) &\
(chunk['operTime'] < next_day)
]
#append dataframe of matching rows to the list
if date_rows.empty:
pass
else:
df_list.append(date_rows)


final_df = pd.concat(df_list)
final_df = final_df.sort_values('operTime')

关于python - 读取csv文件时如何以时间升序方式获取最近一天的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344932/

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