我试图在我的数据帧中找到30天或更久的记录。我几乎所有的工作,但我需要纠正的年龄列格式。程序中的大部分内容都是我在堆栈溢出中找到的,但我不知道如何更改返回的增量的格式。你知道吗
import pandas as pd
import datetime as dt
file_name = '/Aging_SRs.xls'
sheet = 'All'
df = pd.read_excel(io=file_name, sheet_name=sheet)
df.rename(columns={'SR Create Date': 'Create_Date', 'SR Number': 'SR'}, inplace=True)
tday = dt.date.today()
tdelta = dt.timedelta(days=30)
aged = tday - tdelta
df = df.loc[df.Create_Date <= aged, :]
# Sets the SR as the index.
df = df.set_index('SR', drop = True)
# Created the Age column.
df.insert(2, 'Age', 0)
# Calculates the days between the Create Date and Today.
df['Age'] = df['Create_Date'].subtract(tday)
上面最后一行中的计算给出了结果,但它看起来像-197 days +09:39:12
,我需要它只是一个正数197
。我还尝试使用python、pandas和datetime关键字进行搜索。你知道吗
df.rename(columns={'Create_Date': 'SR Create Date'}, inplace=True)
writer = pd.ExcelWriter('output_test.xlsx')
df.to_excel(writer)
writer.save()
我看不到你的示例数据,但IIUC和你只是想得到一个timedelta的天数的绝对值,这应该是可行的:
解释:
给定一个带有timedelta列的数据帧:
您可以使用
dt.days
将天数提取为int
:然后,您需要做的就是将其包装在对
abs
的调用中,以获得该int的绝对值:相关问题 更多 >
编程相关推荐