[英]How to append hour:min:sec to the DateTime in pandas Dataframe
[英]Converting separate hour/min/sec columns into a single time column with pandas?
我正在嘗試創建一個時間列,我可以通過重新采樣日期/時間索引來創建時間序列 plot。 但是我很難將這些列組合成一個單一的列和/或索引它。 下面是我的代碼和我試圖做的事情。 任何建議,將不勝感激!
colnames=['time_ms','power','chisq','stations','alt','hour','min','sec','time_frac','lat','lon']
df = pd.read_csv('/data/selected_lma_matlab_20210914.txt',delim_whitespace=True, header=None, names=colnames)
#df = pd.read_csv('/data/selected_lma_matlab_20210914.txt',delim_whitespace=True, header=None,names=colnames,parse_dates=[[5, 7]], index_col=0)
#df = pd.read_csv('/data/selected_lma_matlab_20210914.txt',delim_whitespace=True, header=None,names=colnames,infer_datetime_format=True,parse_dates=[[5, 6]], index_col=0)
我確實嘗試過這種方法來包含/添加日期,我相信這不是必需的,但會很好地保持一致性。 但是我無法讓它工作。
s = df['hour'].mul(10000) + df['min'].mul(100) + df['sec']
df['date'] = pd.to_datetime('2021-09-14 ' + s.astype(int), format='%Y-%m-%d %H%M%S.%f')
此方法確實可以創建一個新列,但在索引它時遇到了麻煩。
df['time'] = (pd.to_datetime(df['hour'].astype(str) + ':' + df['min'].astype(str), format='%H:%M')
.dt.time)
df['Datetime'] = pd.to_datetime(df['time'])
df.set_index('Datetime')
創建此列以獲取時間序列的計數
df['tot'] = 1
使用它來重新采樣新 df 中時間序列所需的數據
df2 = df[['tot']].resample('5min').sum()
但是,盡管我在上面嘗試過,但我仍然收到日期時間/索引錯誤。
數據鏈接: https://drive.google.com/file/d/16GmXfQNMK81aAbB6C-W_Bjm2mcOVrILP/view?usp=sharing
您應該嘗試將不同列中的所有數據保存為字符串,將它們連接起來,然后將其轉換為數據時間。 下面更新的代碼會這樣做......
colnames=['time_ms','power','chisq','stations','alt','hour','min','sec','time_frac','lat','lon']
df = pd.read_csv('selected_lma_matlab_20210914.txt',delim_whitespace=True, header=None, names=colnames)
df['date'] = '2021-09-14 ' + df['hour'].astype('string') + ":" + df['min'].astype('string') + ":" + df['sec'].astype('string')
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d %H:%M:%S')
df.set_index('date', inplace=True)
發布此內容,您可以根據需要進行繪圖。 我試過這些,它們似乎工作得很好......
df.alt.plot(kind='line')
df.plot('lat', 'lon', kind='scatter')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.