我有一個 CSV,我將其讀入數(shù)據(jù)框以刪除某些列并進(jìn)行一些操作。一些示例行是:20 2/5/1954 13:55 0.5 1821 2/5/1954 14:35 0.5 18.222 2/5/1954 16:35 0.5 18.5我想刪除日期時間中的時間,例如,我得到的2/5/1954不是2/5/1954 13:55.我寫了這個腳本:import pandas as pdfrom datetime import datetime as dtdf = pd.read_csv('habsos_20200310.csv', sep=',', error_bad_lines=False, index_col=False, dtype='unicode')pd.set_option('display.max_rows', None)# Get only the columns we care aboutdfSub = df[['sample_date','sample_depth','water_temp']]# Remove the NaN valuesdfClean = dfSub.dropna()# Select 0.5 depth measurements onlydfClean2 = dfClean.loc[df['sample_depth'] == '0.5']print(dfClean2)這給了我: sample_date sample_depth water_temp20 2/5/1954 13:55 0.5 1821 2/5/1954 14:35 0.5 18.222 2/5/1954 16:35 0.5 18.523 2/5/1954 16:52 0.5 18.524 2/5/1954 17:10 0.5 18.625 2/5/1954 17:25 0.5 18.826 2/5/1954 17:43 0.5 19我試圖將這些行添加到我的腳本中以轉(zhuǎn)換該sample_date列:new_df = dfClean2['sample_date'].str.split()[0]print(new_df)
1 回答

Helenr
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個贊
評論已經(jīng)建議您使用expand=True
.?另一種選擇是
dfClean2.sample_date?=?dfClean2.sample_date.str.split('?').str.get(0)
但是,pandas 為 dtype 實(shí)現(xiàn)了許多方法datetime
。parse_dates=True
我建議您傳遞參數(shù).read_csv()
(使用 read_csv 處理日期時間)并.dt
在該列上使用系列訪問器。
dfClean2.sample_date?=?dfClean2.sample_date.dt.date
添加回答
舉報(bào)
0/150
提交
取消