熊猫:read_csv,其中日期和时间列作为一个datetime列

时间:2020-11-02 15:56:53

标签: python pandas csv

我有带有“日期”和“时间”列的csv文件。

        Date      Time    Asset  Qty     Price Operation           Order   Fee
0  09.08.2020  10:26:11  Si-6.20    1  68675.00       Buy  26010327752252  1.06
1  09.08.2020  10:28:34  BR-7.20    2     40.80      Sell  26010327909139  2.48
2  09.08.2020  10:31:10  BR-7.20    2     40.68      Sell  26010328155020  2.48
3  09.08.2020  13:01:42  Si-6.20    4  68945.00      Sell  26010337903445  4.24
4  09.08.2020  13:01:48  BR-7.20    1     40.04       Buy  26010337907162  1.24

我想要做的是将Date,Time列转换为一个DateTime列。

            DateTIme    Asset  Qty     Price Operation           Order   Fee
0 2020-09-08 10:26:11  Si-6.20    1  68675.00       Buy  26010327752252  1.06
1 2020-09-08 10:28:34  BR-7.20    2     40.80      Sell  26010327909139  2.48
2 2020-09-08 10:31:10  BR-7.20    2     40.68      Sell  26010328155020  2.48
3 2020-09-08 13:01:42  Si-6.20    4  68945.00      Sell  26010337903445  4.24
4 2020-09-08 13:01:48  BR-7.20    1     40.04       Buy  26010337907162  1.24

这是我使用的代码

    df = pd.read_csv('table.csv', sep=';', dtype=dtypes)
    dt = pd.to_datetime(df['Date'] + ' ' + df['Time'])
    df.drop(['Date','Time'], axis=1, inplace=True)
    df.insert(0, 'DateTime', dt)

是否有更优雅的方法来做到这一点?我的意思是在读取csv文件时将日期和时间列转换为一个datetime列。

2 个答案:

答案 0 :(得分:1)

您可以使用apply + lambda组合,它在熊猫中非常流行(通常非常快)

我还使用了f字符串,我觉得它更紧凑,更易读,但仅在Python 3.6+中可用

df = pd.read_csv('table.csv', sep=';', dtype=dtypes)
df["DateTime"] = df.apply(lambda row: pd.to_datetime(f'{row["Date"]} {row["Time"]}'), axis="columns")
df.drop(['Date','Time'], axis=1, inplace=True)

如果您想获得更多的花哨,可以将它们拴在一起:

df = pd.read_csv('table.csv', sep=';', dtype=dtypes)
df["DateTime"] = df.apply(lambda row: pd.to_datetime(f'{row["Date"]} {row["Time"]}'), axis="columns")\
                   .drop(['Date','Time'], axis=1)

答案 1 :(得分:0)

由于您不确定列的顺序,因此我们可以在读取csv之后使用简单的assign,然后使用droprename

import pandas as pd
df = pd.read_csv(file)
df = df.assign(Date=pd.to_datetime(df["Date"] + " " + df["Time"])).drop("Time", 1).rename(
                                                              columns={"Date": "DateTime"})

print(df)
             DateTime    Asset  Qty     Price Operation           Order   Fee
0 2020-09-08 10:26:11  Si-6.20    1  68675.00       Buy  26010327752252  1.06
1 2020-09-08 10:28:34  BR-7.20    2     40.80      Sell  26010327909139  2.48
2 2020-09-08 10:31:10  BR-7.20    2     40.68      Sell  26010328155020  2.48
3 2020-09-08 13:01:42  Si-6.20    4  68945.00      Sell  26010337903445  4.24
4 2020-09-08 13:01:48  BR-7.20    1     40.04       Buy  26010337907162  1.24
相关问题