数据帧索引从日期时间删除日期

2024-06-26 14:54:32 发布

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

文件dataexample_df.txt:

2020-12-04_163024 26.15 26.37 19.40 24.57
2020-12-04_163026 26.15 26.37 19.20 24.57
2020-12-04_163028 26.05 26.37 18.78 24.57

我想将其作为数据帧读取,其中索引列只有格式为'%H:%M:%S'的时间部分,没有日期

import pandas as pd
df = pd.read_csv("dataexample_df.txt", sep=' ', header=None, index_col=0)
print(df)

输出:

                       1      2      3      4
0
2020-12-04_163024  26.15  26.37  19.40  24.57
2020-12-04_163026  26.15  26.37  19.20  24.57
2020-12-04_163028  26.05  26.37  18.78  24.57

然而,想要的输出:

              1      2      3      4
0
16:30:24  26.15  26.37  19.40  24.57
16:30:26  26.15  26.37  19.20  24.57
16:30:28  26.05  26.37  18.78  24.57

我尝试了不同的date_parser=-函数(参见Parse_dates in Pandas中的答案) 但只获取错误消息。还有,有些相关的是Python/Pandas convert string to time only但是运气不好,我被卡住了。我正在使用Python 3.7


Tags: 文件csv数据importtxtpandasdfread
3条回答

考虑到你的df是这样的:

In [121]: df
Out[121]: 
                       1      2      3      4
0                                            
2020-12-04_163024  26.15  26.37  19.40  24.57
2020-12-04_163026  26.15  26.37  19.20  24.57
2020-12-04_163028  26.05  26.37  18.78  24.57

可以将^{}^{}一起使用:

In [122]: df.reset_index(inplace=True)
In [127]: df[0] = pd.to_datetime(df[0].str.replace('_', ' ')).dt.time

In [130]: df.set_index(0, inplace=True)

In [131]: df
Out[131]: 
              1      2      3      4
0                                   
16:30:24  26.15  26.37  19.40  24.57
16:30:26  26.15  26.37  19.20  24.57
16:30:28  26.05  26.37  18.78  24.57

您需要使用format参数告诉它日期的格式(否则会出现错误):

# gives an error:
pd.to_datetime('2020-12-04_163024')

# works:
pd.to_datetime('2020-12-04_163024', format=r'%Y-%m-%d_%H%M%S')

因此,您可以将其应用于数据帧,然后使用dt.time访问时间:

df['time'] = pd.to_datetime(df.index, format=r'%Y-%m-%d_%H%M%S').dt.time

这将为您提供作为对象的时间,但如果您想格式化它,只需使用以下内容:

df['time'] = df['time'].strftime('%H:%M:%S')

在这里,我创建了一个简单的函数来格式化datetime列,请试试这个

import pandas as pd

df = pd.read_csv('data.txt', sep=" ", header=None)

def format_time(date_str):
    # split date and time
    time =  iter(date_str.split('_')[1])
    # retun the time value adding
    return ':'.join(a+b for a,b in zip(time, time))

df[0] = df[0].apply(format_time)

print(df)

相关问题 更多 >