从剪贴板读取带有日期时间列的数据帧

2024-03-28 23:18:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我看到许多张贴到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

我仍然没有找到一个好方法,可以使用^{}(在^{} 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)时,我得到了相同的异常

其他人是如何做到这一点的


Tags: orcolumnsandof参数dateifnames
2条回答

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

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']]

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

          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

是的,这不是一个完全自动化的过程,但只要处理要复制的小数据帧,它就不是那么糟糕。尽管我愿意看到更好的选择

相关问题 更多 >