首页 > 解决方案 > 如何使用其中一行中可用的 TIMESTAMP 值在数据框中为所有行设置日期

问题描述

我有这种格式的数据:

23:11:16 xyz
23:14:30 xyz
23:26:15 TIMESTAMP 3/23/2020
23:32:31 xyz
0:00:26  xyz
0:00:30  xyz
0:00:55  TIMESTAMP 3/24/2020
0:01:30  xyz

我想把它转换成这种格式:

3/23/2020 23:11:16 xyz
3/23/2020 23:14:30 xyz
3/23/2020 23:26:15 TIMESTAMP 3/23/2020
3/23/2020 23:32:31 xyz
3/24/2020 0:00:26  xyz
3/24/2020 0:00:30  xyz
3/24/2020 0:00:55  TIMESTAMP 3/24/2020
3/24/2020 0:01:30  xyz

我是编码初学者,任何帮助将不胜感激。

到目前为止,我已经使用以下代码使其工作:

#get index for all values with Timestamp
s=account[account['Other'].str.contains('TIMESTAMP', na=False)].index

#assign the date for those indexes
account.loc[s, 'Date'] = account.Other.str.split('\s+').str[2]

#fetch the first date from indexing
a = account.loc[s[0], 'Date']

#iterate thru rows to populate the date
for row in account.itertuples():
    if pd.isnull(account.at[row.Index, 'Date']):
        account.at[row.Index, 'Date'] = a
    elif pd.notnull(account.at[row.Index, 'Date']):
        a = account.at[row.Index, 'Date']

这只是一段代码

此代码的问题在于,它没有考虑到日期的变化,并继续填充日期,直到观察到下一个“TIMESTAMP”

标签: python-3.xpandasdataframe

解决方案


推荐阅读