我有一個標題看起來像這樣的資料框。我想使用字串拆分方法創建兩個單獨的列:一列用于日期,一列用于時間。
Date/Time Lat Lon Base
0 7/1/2014 0:03:00 40.7586 -73.9706 B02512
1 7/1/2014 0:05:00 40.7605 -73.9994 B02512
2 7/1/2014 0:06:00 40.7320 -73.9999 B02512
3 7/1/2014 0:09:00 40.7635 -73.9793 B02512
4 7/1/2014 0:20:00 40.7204 -74.0047 B02512
所以是這樣的:
Date Time Lat Lon Base
0 7/1/2014 0:03:00 40.7586 -73.9706 B02512
1 7/1/2014 0:05:00 40.7605 -73.9994 B02512
2 7/1/2014 0:06:00 40.7320 -73.9999 B02512
3 7/1/2014 0:09:00 40.7635 -73.9793 B02512
4 7/1/2014 0:20:00 40.7204 -74.0047 B02512
uj5u.com熱心網友回復:
您可以使用:
out = pd.concat([df.pop('Date/Time').str.extract('(?P<Date>[^\s]*)\s(?P<Time>.*)'),
df], axis=1)
print(out)
# Output
Date Time Lat Lon Base
0 7/1/2014 0:03:00 40.7586 -73.9706 B02512
1 7/1/2014 0:05:00 40.7605 -73.9994 B02512
2 7/1/2014 0:06:00 40.7320 -73.9999 B02512
3 7/1/2014 0:09:00 40.7635 -73.9793 B02512
4 7/1/2014 0:20:00 40.7204 -74.0047 B02512
uj5u.com熱心網友回復:
這是我所做的: import pandas as pd
date, time = [],[]
for i in df['Date/Time']:
to_append = i.split(' ') #Separates date and time for example: [date,time]
date.append(to_append[0]) #Appending the dates
time.append(to_append[1]) #Appending the times
df.pop('Date/Time') #Removing the old Date/Time
df.insert(0,'Date',date) #Creating Date Column at Start
df.insert(1,'Time',time) #Creating Time Column at Index 1
print(df)
Output: Date Time Lat Lon Base
0 7/1/2014 0:03:00 40.7586 -73.9706 B02512
1 7/1/2014 0:05:00 40.7605 -73.9994 B02512
2 7/1/2014 0:06:00 40.7320 -73.9999 B02512
3 7/1/2014 0:09:00 40.7635 -73.9793 B02512
4 7/1/2014 0:20:00 40.7204 -74.0047 B02512
uj5u.com熱心網友回復:
只需使用拆分
df['date'] = df['date'].apply(lambda x : x.split(' ')[0])
df['Time'] = df['date'].apply(lambda x : x.split(' ')[1))
uj5u.com熱心網友回復:
您可以決議日期時間字串并在空間上拆分,也可以將列轉換為日期時間并獲取日期組件或時間組件
data="""Index,Date/Time,Lat,Lon,Base
0,7/1/2014 0:03:00,40.7586,-73.9706,B02512
1,7/1/2014 0:05:00,40.7605,-73.9994,B02512
2,7/1/2014 0:06:00,40.7320,-73.9999,B02512
3,7/1/2014 0:09:00,40.7635,-73.9793,B02512
4,7/1/2014 0:20:00,40.7204,-74.0047,B02512"""
df=pd.read_csv(StringIO(data),sep=',')
print(df['Date/Time'])
df['Date']=df['Date/Time'].apply(lambda x: x.split(' ')[0])
df['Time']=df['Date/Time'].apply(lambda x: x.split(' ')[1])
df['Date/Time']=pd.to_datetime(df['Date/Time'])
df['Date']=df['Date/Time'].dt.date
df['Time']=df['Date/Time'].dt.time
print(df['Time'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/444453.html
