基于参数化计算生成字段的Python脚本

2024-06-16 12:35:02 发布

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

我对python还很陌生,收到了一个有趣的请求。我有一个这样的结果集,但规模要大得多,包括多个不同的账号

acct no.   date         Event
11111111   2012/01/01   1
11111111   2012/01/05   1

我将附加一个辅助日期对象,该对象将结果集转换为以下输出:

acct no.   date         Event
11111111   2012/01/01   1
11111111   2012/01/02   0
11111111   2012/01/03   0
11111111   2012/01/04   0
11111111   2012/01/05   1
11111111   2012/01/06   0

请求如下:

我被要求构建一个脚本,它可以测量两个日期之间的距离,计算差值(以天数为单位),并在距离达到该距离时生成一个标志。棘手的部分是当有一个新的记录集时,我需要将第一个记录集的结果附加到下一个记录集,然后继续计算和标记生成。你知道吗

最终输出应该如下所示:

acct no.   date         Event  Recent
11111111   2012/01/01   1      Y
11111111   2012/01/02   0      Y
11111111   2012/01/03   0      N
11111111   2012/01/04   0      N
11111111   2012/01/05   1      Y
11111111   2012/01/06   0      Y

我对python还比较了解,不知道从哪里开始。你知道吗

非常感谢您的帮助。你知道吗

谢谢你


Tags: 对象no脚本event距离date标志单位
1条回答
网友
1楼 · 发布于 2024-06-16 12:35:02

从您的问题来看,似乎您能够计算日期差异,只是在将“最近”标志附加到文件中的每一行时遇到了问题。假设您正在从文本文件中读取帐户信息,下面是一些可以帮助您开始的内容。如果您的信息位于名为accounts.txt的文件中:

import shutil

recentFlag = 'Y' # Example only. It sounds like you have your own way of determining this
filename = 'accounts.txt'

shutil.copy(filename, filename+'~') # Save a backup copy of the file you're editing.
                                    # We will read from this file and write to the original


fIn = open(filename+'~', 'r')
fOut = open(filename, 'w')


header = fIn.readline() # Read the first (header) line from your file, and write it to the output file. If the real file has multiple header lines, loop this
fOut.write(header + '\tRecent')

for line in fIn:
  fOut.write(line + '\t' + recentFlag + '\n')
  fOut.flush()

fIn.close()
fOut.close()

快乐的编码!你知道吗

相关问题 更多 >