python - 格式化 NumPy 数组中的日期数据

标签 python arrays numpy datetime data-science

非常感谢您的建议。我做了一个如下所示的练习:

The first column (index 0) contains year values as four digit numbers in the format YYYY (2016, since all trips in our data set are from 2016). Use assignment to change these values to the YY format (16) in the test_array ndarray.

我用一段代码解决了:

test_array[:,0] = test_array[:,0]%100

但我确信它必须是更通用和更智能的方法才能使用日期时间或其他方法获得相同的结果。但我找不到它。我尝试了这段代码的不同变体,但我没有弄错:

dt.datetime.strptime(str(test_array[:,0]), "%Y")
test_array[:,0] = dt.datetime.strftime("%y")

你能帮我解决这个问题吗?

谢谢

最佳答案

为了将年份从 YYYY 格式转换为 YY 格式,需要中间 datetime 值,可以按以下方式对其执行 strftime 等操作:

df.iloc[:, 0] = df.iloc[:, 0].apply(lambda x: pd.datetime(x, 1, 1).strftime('%y'))

这里要获取 datetime 值,我们需要 3 个参数:年、月和日,其中我们有年,其余值默认为 1。

关于python - 格式化 NumPy 数组中的日期数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54805749/

相关文章:

python - 缺少数据的 python 中的 Pct_change

python - QGraphicsScene 将选择保留在空选择框上

python - 为什么 "not(True) in [False, True]"返回 False?

python - 使用 SFrame 和 SArray 与 Graphlab 和/或 Numpy 进行矩阵乘法

python - 使用 Python 自动调整 Excel 工作表的所有列

php - 如何循环遍历 $_FILES 数组的多维数组

C++,从 char 数组中提取带符号的多位整数

python - Cython:将内存 View 转换为 NumPy 数组

python - 使用 `numpy.take` 随机选择 2d 个点

python - 达到内存限制时退出 Python 程序