pandas 将“现在”时间戳列添加到熊猫 df
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25354368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add a 'now' timestamp column to a pandas df
提问by Luis Miguel
I have the following code:
我有以下代码:
s1 = pd.DataFrame(np.random.uniform(-1,1,size=10))
s2 = pd.DataFrame(np.random.normal(-1,1, size=10))
s3 = pd.concat([s1, s2], axis=1)
s3.columns = ['s1','s2']
Which generates a DF that looks like this:
这会生成一个如下所示的 DF:
s1 s2
0 -0.841204 -1.857014
1 0.961539 -1.417853
2 0.382173 -1.332674
3 -0.535656 -2.226776
4 -0.854898 -0.644856
5 -0.538241 -2.178466
6 -0.761268 -0.662137
7 0.935139 0.475334
8 -0.622293 -0.612169
9 0.872111 -0.880220
How can I add a column (or replace the index 0-9), by a timestamp with the now time? The np array will not always have size 10
如何通过带有现在时间的时间戳添加列(或替换索引 0-9)?np 数组的大小并不总是 10
回答by EdChum
You can use datetime's nowmethod to create the time stamp and either assign this to a new column like: s3['new_col'] = dt.datetime.now()or assign direct to the index:
您可以使用 datetime 的now方法来创建时间戳,并将其分配给一个新列,例如:s3['new_col'] = dt.datetime.now()或直接分配给索引:
In [9]:
import datetime as dt
s3.index = pd.Series([dt.datetime.now()] * len(s3))
s3
Out[9]:
s1 s2
2014-08-17 23:59:35.766968 0.916588 -1.868320
2014-08-17 23:59:35.766968 0.139161 -0.939818
2014-08-17 23:59:35.766968 -0.486001 -2.524608
2014-08-17 23:59:35.766968 0.739789 -0.609835
2014-08-17 23:59:35.766968 -0.822114 -0.304406
2014-08-17 23:59:35.766968 -0.050685 -1.295435
2014-08-17 23:59:35.766968 -0.196441 -1.715921
2014-08-17 23:59:35.766968 -0.421514 -1.618596
2014-08-17 23:59:35.766968 -0.695084 -1.241447
2014-08-17 23:59:35.766968 -0.541561 -0.997481
Note that you are going to get a lot of duplicate values in your index due to the resolution and speed of the assignment, not sure how useful this is, better to have it as a separate column in my opinion.
请注意,由于分配的分辨率和速度,您将在索引中获得大量重复值,不确定这有多大用处,我认为最好将其作为单独的列。

