【问题标题】:Pandas read DataFrame with datetime columns from clipboardPandas 从剪贴板读取带有日期时间列的 DataFrame
【发布时间】:2018-07-05 02:01:58
【问题描述】:

我看到很多 DataFrames 发布到 StackOverflow,看起来像:

          a                  dt         b
0 -0.713356 2015-10-01 00:00:00 -0.159170
1 -1.636397 2015-10-01 00:30:00 -1.038110
2 -1.390117 2015-10-01 01:00:00 -1.124016

我还没有找到使用.read_clipboard.read_table docs 中的参数列表)将这些复制到我的解释器的好方法。

我以为关键是parse_dates参数:

parse_dates : boolean or list of ints or names or list of lists or dict, default False
* boolean. If True -> try parsing the index.
* list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
* list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
* dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

pd.read_clipboard(parse_dates={'dt': [1, 2]}) 引发异常 NotImplementedError: file structure not yet supported

当我尝试跳过第一行 pd.read_clipboard(parse_dates=[[1, 2]], names=['a', 'dt1', 'dt2', 'b'], skiprows=1, header=None) 时,我得到了同样的异常。

其他人是怎么做到的?

【问题讨论】:

  • 大量手动格式化,就我而言...
  • 通常,各个列之间有两个空格。这使事情变得更容易。如果不是这样,你是 SOL,你必须自己做一些手动格式化。

标签: python pandas dataframe datetime clipboard


【解决方案1】:

如果它对某人有帮助,这就是我现在所做的:

df = pd.read_clipboard(skiprows=1, names=['a', 'dt1', 'dt2', 'b'])
df['dt'] = pd.to_datetime(df['dt1'] + ' ' + df['dt2'])
df = df[['a', 'dt', 'b']]

【讨论】:

    【解决方案2】:

    这就是我所做的。首先,确保您的列之间有两个空格:

              a                  dt         b
    0 -0.713356  2015-10-01 00:00:00  -0.159170
    1 -1.636397  2015-10-01 00:30:00  -1.038110
    2 -1.390117  2015-10-01 01:00:00  -1.124016
    

    注意,datetime 列在日期和时间之间有一个空格。这个很重要。接下来,我使用类似这样的东西来加载它:

    df = pd.read_clipboard(sep='\s{2,}', parse_dates=[1], engine='python')
    df
    
                 a                  dt         b
    0  0 -0.713356 2015-10-01 00:00:00 -0.159170
    1  1 -1.636397 2015-10-01 00:30:00 -1.038110
    2  2 -1.390117 2015-10-01 01:00:00 -1.124016
    

    df.dtypes
    
    a             object
    dt    datetime64[ns]
    b            float64
    dtype: object
    

    是的,这不是一个完全自动化的过程,但只要您处理要复制的小数据框,它就那么不好。虽然我乐于看到更好的选择。

    【讨论】:

    • 对于小型 DataFrame 来说可能比我目前的方法更容易。
    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 2017-02-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2018-09-16
    相关资源
    最近更新 更多