【问题标题】:How to filter csv data to remove data after a specified year?如何过滤 csv 数据以在指定年份后删除数据?
【发布时间】:2020-08-06 18:46:52
【问题描述】:

我正在用 python 读取一个包含多列的 csv。

第一列是日期,我必须删除对应于 2017 年之前年份的行。

           time      high        low  Volume      Plot     Rango
0    2017-12-22  25.17984  24.280560     970  0.329943  0.899280
1    2017-12-26  25.17984  23.381280    2579  1.057921  1.798560
2    2017-12-27  25.17984  23.381280    2499  0.998083  1.798560
3    2017-12-28  25.17984  24.280560    1991  0.919885  0.899280
4    2017-12-29  25.17984  24.100704    2703  1.237694  1.079136
..          ...       ...        ...     ...       ...       ...
580  2020-04-16   5.45000   4.450000  117884  3.168380  1.000000
581  2020-04-17   5.35000   4.255200   58531  1.370538  1.094800
582  2020-04-20   4.66500   4.100100   25770  0.582999  0.564900
583  2020-04-21   4.42000   3.800000   20914  0.476605  0.620000
584  2020-04-22   4.22000   3.710100   23212  0.519275  0.509900

我想删除2018年之前对应年份的行,所以2017,2016,2015...应该删除

我正在尝试这个但不起作用

if 2017 in datos['time']: datos['time'].remove()  #check if number 2017 is in each of the items of the column 'time'

日期被识别为数字,而不是数据时间,但我认为我不需要将其声明为数据时间。

【问题讨论】:

  • 如果您可以使用 pandas,请将 csv 加载到其中并使用标准 pandas 方法过滤行。

标签: list csv row remove-if


【解决方案1】:

pandas

  • 根据您的数据
  • 使用Boolean indexing
  • time 必须是 datetime64[ns] 格式
    • df.info() 将给 dtypes
    • df['date'] = pd.to_datetime(df['date'])
df[df['time'].dt.year >= 2018]

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2021-03-24
    • 2020-11-21
    • 2016-05-22
    • 2019-11-03
    • 2020-10-24
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多