【问题标题】:How to set timestamp as an index for a data frame in R如何将时间戳设置为R中数据帧的索引
【发布时间】:2019-04-03 01:42:51
【问题描述】:

我有一个名为“试用”的数据框。我已将数据框中的日期和时间组合在一起,以获得一个具有 POSIXct 时间戳的字段。我想将此组合日期时间或时间戳设置为我的数据框“试用”的索引,我该怎么做?我已经看到了类似的问题,但没有成功。 代码如下:

 trial <- read.csv("2018_05_04_h093500.csv", header=TRUE, skip = 16, sep=",")
 trial$Date <- with(trial, as.POSIXct(paste(as.Date(Date, format="%Y/%m/%d"), Time)))
 dtPOSIXct <- as.POSIXct(trial$Date )
 dtTime <- as.numeric(dtPOSIXct - trunc(dtPOSIXct, "days"))
 class(dtTime) <- "POSIXct"

【问题讨论】:

  • 可能是format(Sys.time(), "%a_%b_%d_%Y")?不过你的问题还不清楚。
  • 我希望时间戳作为数据帧的索引,就像在 python 中一样:trial.index=pd.to_datetime(trial.Date+" "+trial.Time

标签: r dataframe indexing


【解决方案1】:

如果您说的是在 Pandas 中相当于 R 的行名,它们不能是 POSIXct 日期时间,它们必须是字符。

# sample data
x <- data.frame('a' = 1:3, 'b' = c('a', 'b', 'c'))
print(x)

#                    a b
#2018-01-01 15:51:33 1 a
#2018-01-04 11:42:31 2 b
#2018-01-07 22:04:41 3 c

dates <- c('2018-01-01 15:51:33', '2018-01-04 11:42:31', '2018-01-07 22:04:41')
rownames(x) <- as.POSIXct(dates, format = '%Y-%m-%d %H:%M:%S')
print(class(rownames(x)[1]))
# [1] "character"

也就是说,您仍然可以在评估时强制它们使用 POSIXct(或任何其他类,很明显),但代价是一些开销和代码混乱:

# print x where rownames, when coerced to POSIXct, represent dates after d
d <- as.POSIXct('2018-01-03 00:00:00', '%Y-%m-%d %H:%M:%S')
x[as.POSIXct(rownames(x), format = f) > d, ]

#                    a b
#2018-01-04 11:42:31 2 b
#2018-01-07 22:04:41 3 c

但是,也许更简单的方法是让任意列有效地充当日期时间索引:

x$date <- as.POSIXct(dates, format = '%Y-%m-%d %H:%M:%S')
class(x$date[1])
# [1] "POSIXct" "POSIXt" 

【讨论】:

  • 感谢您的及时回复。问题是如何将时间戳作为索引?并且任意列索引无济于事。如何将此时间戳作为索引。我有很多这样的文件。
  • 快速回答是,你不能。如果您可以将它们强制为字符,那么rownames(x) &lt;- timestamps
  • 好的。 rownames(x)
  • 这只是一般情况,在您的具体示例中为rownames(trial) &lt;- trial$Date。同样,R 数据帧中 [pandas] 索引的等价物是行名。可惜没有set_index()这样的方法。
  • 我已将 trial$Date 转换为如下字符:trial$Date
猜你喜欢
  • 1970-01-01
  • 2019-03-01
  • 2014-12-09
  • 1970-01-01
  • 2016-10-05
  • 2015-12-28
  • 2020-11-18
  • 2020-08-13
  • 1970-01-01
相关资源
最近更新 更多