[英]Pandas: read_csv with date and time columns as one datetime column
我有帶有“日期”和“時間”列的 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
我想要做的是在一個 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 文件時在一個日期時間列中轉換日期和時間列。
您可以使用在熊貓中非常流行(並且通常非常快)的 apply+lambda 組合
我還使用了一個 f-string,我發現它更緊湊和可讀,但僅在 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)
由於您不確定您的列的順序,我們可以在您閱讀 csv 后使用簡單的assign
,然后drop
rename
.
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.