[英]pandas dataframe index remove date from datetime
文件 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
我想将其读取为 pandas dataframe ,其中索引列只有格式为'%H:%M:%S'
的时间部分,没有日期。
import pandas as pd
df = pd.read_csv("dataexample_df.txt", sep=' ', header=None, index_col=0)
print(df)
Output:
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
但是,想要 output:
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=
-functions(参见Pandas 中 Parse_dates 中的答案),但只收到错误消息。 此外,有些相关的是Python/Pandas 仅将字符串转换为时间,但没有运气,我被卡住了。 我正在使用 Python 3.7。
考虑到你的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
您可以将Series.replace
与Series.dt.time
一起使用:
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
在这里,我创建了一个简单的 function 来格式化您的日期时间列,请试试这个。
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)
您需要使用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')
因此,您可以将其应用于您的 dataframe ,然后使用dt.time
访问时间:
df['time'] = pd.to_datetime(df.index, format=r'%Y-%m-%d_%H%M%S').dt.time
这将为您提供 object 的时间,但如果您想格式化它,只需使用以下内容:
df['time'] = df['time'].strftime('%H:%M:%S')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.