gpt4 book ai didi

pandas - 选择第n行作为Pandas DataFrame,而不读取整个文件

转载 作者:行者123 更新时间:2023-12-04 23:12:27 28 4
gpt4 key购买 nike

我正在读取一个包含约950万行x 16列的大文件。

我对检索代表性样本感兴趣,并且由于数据是按时间组织的,因此我想通过选择第500个元素来做到这一点。

我能够加载数据,然后选择第500行。

我的问题:是否可以立即读取第500个元素(使用.pd.read_csv()或其他方法),而不必先读取然后过滤数据?

问题2:如果未订购日期列,您将如何解决此问题?目前,我假设它是按日期排序的,但是所有数据都容易出错。

以下是数据的摘要(前五行)前四行乱序,其余数据集按时间排序(按时间):

VendorID    tpep_pickup_datetime    tpep_dropoff_datetime   passenger_count trip_distance   RatecodeID  store_and_fwd_flag  PULocationID    DOLocationID    payment_type    fare_amount extra   mta_tax tip_amount  tolls_amount    improvement_surcharge   total_amount
0 1 2017-01-09 11:13:28 2017-01-09 11:25:45 1 3.30 1 N 263 161 1 12.5 0.0 0.5 2.00 0.00 0.3 15.30
1 1 2017-01-09 11:32:27 2017-01-09 11:36:01 1 0.90 1 N 186 234 1 5.0 0.0 0.5 1.45 0.00 0.3 7.25
2 1 2017-01-09 11:38:20 2017-01-09 11:42:05 1 1.10 1 N 164 161 1 5.5 0.0 0.5 1.00 0.00 0.3 7.30
3 1 2017-01-09 11:52:13 2017-01-09 11:57:36 1 1.10 1 N 236 75 1 6.0 0.0 0.5 1.70 0.00 0.3 8.50
4 2 2017-01-01 00:00:00 2017-01-01 00:00:00 1 0.02 2 N 249 234 2 52.0 0.0 0.5 0.00 0.00 0.3 52.80

最佳答案

Can I immediately read every 500th element (using.pd.read_csv() or some other method), without having to read first and then filter my data?



您可以做的就是在 skiprows 中使用 read_csv参数,该参数接受类似列表的参数来丢弃感兴趣的行(并因此选择)。因此,您可以创建一个长度等于要读取的行数的 np.arange ,并使用 500th 从其中删除每个 np.delete元素,这样,我们将只读取第500行:
n_rows = 9.5e6
skip = np.arange(n_rows)
skip = np.delete(skip, np.arange(0, n_rows, 500))
df = pd.read_csv('my_file.csv', skiprows = skip)

关于pandas - 选择第n行作为Pandas DataFrame,而不读取整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53812094/

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