簡體   English   中英

如何拆分pandas數據幀列中的所有字符串?

[英]How to split all strings in a column of pandas dataframe?

我有一個帶有createdOnTimeZone和startDate列的數據集。 時區就像-600但是startDates就像2019-01-28T19:50:27.345-06:00。 我想在所有行中將startzone應用於startDate。 我知道我必須在''上分割startDate。 (我不需要毫秒,直到第二個就夠了),使用strptime將其轉換為日期時間,然后使用mktime將日期時間轉換為時間戳。 但我不知道如何在startDate列中的所有行上應用它。

createdOnTimeZone startDate
-600              2019-01-28T19:50:27.345-06:00
-600              2019-01-28T19:50:35.493-06:00
-600              2019-01-28T19:50:38.947-06:00
-600              2019-01-28T19:50:49.048-06:00
-600              2019-01-28T19:50:59.600-06:00
-600              2019-01-28T19:51:08.267-06:00
-600              2019-01-28T19:51:15.899-06:00
-600              2019-01-28T19:51:27.326-06:00
-600              2019-01-28T19:51:38.762-06:00

試試這個:

df['startDate'] = df['startDate'].apply(lambda x : x.split('.')[0])

這將用“。”分隔字符串。

恩。

2019-01-28T19:50:27.345-06:00變為2019-01-28T19:50:27

這是時間戳

df['startDate'] = df['startDate'].apply(lambda x : time.mktime(datetime.datetime.strptime(x.split('.')[0], "%Y-%m-%dT%H:%M:%S").timetuple()))

嘗試這個:

from datetime import datetime

a = "2019-01-28T19:50:27.345-06:00"

# Splitting the string and grabbing the zeroth index, which is the date.
date = a.split("T")[0]

# Similarly splitting and grabbing the time, removing the milliseconds.
time = a.split("T")[1].split(".")[0]

# Converted it to my desired datetime format and extracted timestamp out of it.
date_time = date + " " + time
time_stamp = datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S").timestamp()

print(type(date_time), date_time)
print(type(time_stamp), time_stamp)
  • 輸出:
<class 'str'> 2019-01-28 19:50:27
<class 'float'> 1548726627.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM