简体   繁体   English

Python:将小时数连接到数据文件中的dd / mm / yyyy列

[英]Python: Concatenate Hour into dd/mm/yyyy column in data file

I have the following file: 我有以下文件:

01/03/2019,23,24.0
01/03/2019,22,24.5
01/03/2019,21,25.9
01/03/2019,20,26.4
01/03/2019,19,26.6
01/03/2019,18,25.9

Where column 1 is date (dd/mm/yyyy), column 2 is hour and column 3 is temperature. 第1列是日期(dd / mm / yyyy),第2列是小时,第3列是温度。

How can I merge columns 1 and 2 in order to make a new column dd/mm/yyyy hh:00, by using pyhton? 如何通过使用pyhton合并第1列和第2列以创建新列dd / mm / yyyy hh:00?

I am using a .csv file and pandas module. 我正在使用.csv文件和pandas模块。

Using csv OR pandas library (tested using python 3.7) 使用csv或pandas库(使用python 3.7测试)

import csv
import pandas as pd

use_pandas = True

if use_pandas:
    df = pd.read_csv('55089401.csv', header=None)
    df[3] = df[0].map(str) + ' ' + df[1].map(str) + ':00'
    del df[0]
    del df[1]
    new_order = [1, 0]
    df = df[df.columns[new_order]]
    print(df)
else:
    out_data = []
    with open('55089401.csv', 'r') as f_in:
        reader = csv.reader(f_in)
        for row in reader:
            out_data.append(['{} {}:00'.format(row[0], row[1]), row[2]])
    with open('55089401_out.csv', 'w', newline='') as f_out:
        writer = csv.writer(f_out)
        writer.writerows(out_data)

Pandas output 熊猫输出

0  01/03/2019 23:00  24.0
1  01/03/2019 22:00  24.5
2  01/03/2019 21:00  25.9
3  01/03/2019 20:00  26.4
4  01/03/2019 19:00  26.6
5  01/03/2019 18:00  25.9

Input file 输入文件

01/03/2019,23,24.0
01/03/2019,22,24.5
01/03/2019,21,25.9
01/03/2019,20,26.4
01/03/2019,19,26.6
01/03/2019,18,25.9

Output file (csv) 输出文件(csv)

01/03/2019 23:00,24.0
01/03/2019 22:00,24.5
01/03/2019 21:00,25.9
01/03/2019 20:00,26.4
01/03/2019 19:00,26.6
01/03/2019 18:00,25.9

Iterate over the lines in the input file, and output with the appended column 遍历输入文件中的各行,并与附加列一起输出

with open('filename.csv') as fin:
    for inputLine in fin:
        x = inputLine.split(',')
        outputLine = inputLine + ',' + str(x[0]) + ' ' + str(x[1]) + ':00'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM