【问题标题】:Pandas and csv import into dataframe. How to best to combine date anbd date fields into onePandas 和 csv 导入数据框。如何最好地将日期和日期字段合并为一个
【发布时间】:2014-01-14 15:14:36
【问题描述】:

我有一个 csv 文件,我正在尝试将其导入 pandas。

有两列兴趣。日期和小时,是前两个列。

E.g.

date,hour,...
10-1-2013,0,
10-1-2013,0,
10-1-2013,0,
10-1-2013,1,
10-1-2013,1,

如何使用 pandas 导入,以便将小时和日期结合起来,或者最好在初始导入后完成?

df = DataFrame.from_csv('bingads.csv', sep=',')

如果我进行初始导入,如何将两者组合为日期然后删除小时?

谢谢

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    定义你自己的date_parser:

    In [291]: from dateutil.parser import parse
    In [292]: import datetime as dt
    In [293]: def date_parser(x):
       .....:     date, hour = x.split(' ')
       .....:     return parse(date) + dt.timedelta(0, 3600*int(hour))
    
    In [298]: pd.read_csv('test.csv', parse_dates=[[0,1]], date_parser=date_parser)
    Out[298]: 
                date_hour  a  b  c
    0 2013-10-01 00:00:00  1  1  1
    1 2013-10-01 00:00:00  2  2  2
    2 2013-10-01 00:00:00  3  3  3
    3 2013-10-01 01:00:00  4  4  4
    4 2013-10-01 01:00:00  5  5  5
    

    【讨论】:

      【解决方案2】:

      应用 read_csv 而不是 read_clipboard 来处理您的实际数据:

      >>> df = pd.read_clipboard(sep=',')
      >>> df['date'] = pd.to_datetime(df.date) + pd.to_timedelta(df.hour, unit='D')/24
      >>> del df['hour']
      >>> df
                       date  ...
      0 2013-10-01 00:00:00  NaN
      1 2013-10-01 00:00:00  NaN
      2 2013-10-01 00:00:00  NaN
      3 2013-10-01 01:00:00  NaN
      4 2013-10-01 01:00:00  NaN
      
      [5 rows x 2 columns]
      

      【讨论】:

      • 打印 pd.__version__=0.10.1
      • df['date'] = pd.to_datetime(df.date) + pd.to_timedelta(df.hour, unit='D')/24 AttributeError: 'module' object has no attribute ' to_timedelta'
      【解决方案3】:

      看看 pandas.read_csv 接受的 parse_dates 参数。 您可以执行以下操作:

      df = pandas.read_csv('some.csv', parse_dates=True)
      # in which case pandas will parse all columns where it finds dates
      df = pandas.read_csv('some.csv', parse_dates=[i,j,k])
      # in which case pandas will parse the i, j and kth columns for dates
      

      【讨论】:

      • 那行不通,只会为第一列生成日期时间,第二列将被读取为 int,您的第二行代码也会失败,因为您想合并列你想成为一个单一的日期时间列,你所做的就是提供一个列列表来尝试解析,所以你需要传递一个列表列表[[i,j,k]],这仍然是无关紧要的,因为内置的日期解析器失败了所以您必须使用自定义 date_parser,例如 @waitingkuo 的答案或 @alko 的方法
      【解决方案4】:

      由于您只使用 cdv 文件中的两列并将它们组合成一个列,因此我将挤入一系列日期时间对象,如下所示:

      import pandas as pd 
      from StringIO import StringIO
      import datetime as dt
      
      txt='''\
      date,hour,A,B
      10-1-2013,0,1,6
      10-1-2013,0,2,7
      10-1-2013,0,3,8
      10-1-2013,1,4,9
      10-1-2013,1,5,10'''
      
      def date_parser(date, hour):
          dates=[]
          for ed, eh in zip(date, hour):
              month, day, year=list(map(int, ed.split('-')))
              hour=int(eh)
              dates.append(dt.datetime(year, month, day, hour))
      
          return dates    
      
      p=pd.read_csv(StringIO(txt), usecols=[0,1], 
                    parse_dates=[[0,1]], date_parser=date_parser, squeeze=True)
      
      print p
      

      打印:

      0   2013-10-01 00:00:00
      1   2013-10-01 00:00:00
      2   2013-10-01 00:00:00
      3   2013-10-01 01:00:00
      4   2013-10-01 01:00:00
      Name: date_hour, dtype: datetime64[ns]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 2021-05-29
        相关资源
        最近更新 更多