【问题标题】:How to add a date from filename to a time column to make datetime column? Python Pandas如何将文件名中的日期添加到时间列以制作日期时间列?蟒蛇熊猫
【发布时间】:2018-10-24 12:52:58
【问题描述】:

我有多个这样命名的文件
2018-08-31-logfile-device1 2018-09-01-logfile-device1

在这些文件中,数据以这种方式排序:
00:00:00.283672analogue values:[2511, 2383, 2461, 2472] 00:00:00.546165analogue values:[2501, 2395, 2467, 2465]

我使用以下代码将所有这些文件附加到一个大数据框中:(我从这里得到:Import multiple excel files into python pandas and concatenate them into one dataframe

file_log = os.listdir(path)
file_log = [file_log for file_log in glob.glob('*device1*')]
df = pd.DataFrame()
for file_log in file_log:
    data = pd.read_csv(file_log,sep='analogue values:',names=['time', 
'col'], engine='python')
    df = data.append(data1)

我转换数据,然后它看起来像这样:
analog1 analog2 analog3 analog4 time 2511 2383 2461 2472 00:00:00.283672 2501 2395 2467 2465 00:00:00.546165 2501 2395 2467 2465 00:00:00.807846 2497 2381 2461 2467 00:00:01.070540 2485 2391 2458 2475 00:00:01.332163

但问题是,我希望时间列是日期时间,其中日期是来自文件名的日期。

analog1 analog2 analog3 analog4 datetime 2511 2383 2461 2472 2018-08-31 00:00:00.283672 2501 2395 2467 2465 2018-08-31 00:00:00.546165 2501 2395 2467 2465 2018-08-31 00:00:00.807846 2497 2381 2461 2467 2018-08-31 00:00:01.070540 2485 2391 2458 2475 2018-08-31 00:00:01.332163

【问题讨论】:

  • 你创建大DataFrame的代码是什么?您可以将其添加到问题中吗?
  • 我添加了代码

标签: python pandas date datetime


【解决方案1】:

您可以将 file[:10] 文件名中的前 10 个值转换为日期时间,并添加到 to_timedelta 转换的列 time

然后append每个DataFrame列出并最后使用concat

dfs = []
for file in glob.glob('*device1*'):
    data = pd.read_csv(file,sep='analogue values:',names=['time','col'], engine='python')
    data['datetime'] = pd.to_datetime(file[:10]) + pd.to_timedelta(data['time'])
    data = data.drop('time', axis=1)
    dfs.append(data)

df = pd.concat(dfs, ignore_index=True)

【讨论】:

  • 是的!非常感谢我自己用 data['datetime'] = pd.to_datetime(file[:10]) + pd.to_timedelta(data['time']) 尝试了类似的事情,但它没有按照我想要的方式进行.
猜你喜欢
  • 2020-12-01
  • 2020-12-16
  • 2017-05-22
  • 2015-07-31
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多