亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將文本日期轉換為年+月進行排序(即 1/19/2019 到 201901)

將文本日期轉換為年+月進行排序(即 1/19/2019 到 201901)

狐的傳說 2022-05-24 12:44:30
我的 sql 數據庫(tests.db)表(三角形)中有一個名為paiddate 的列。例如,它是一個看起來像的文本字段'1/19/2019'。在另一個名為paidmonth 的列中,我想要類似的東西'201901',這將允許我按年和月對數據進行排序。我試過 -def getYearMonth(s):   return s.split("/")[0]+"-"+s.split("/")[2]df['paidmonth']= df['paiddate'].apply(lambda x: getYearMonth(x))這給了我 1-2019,看起來不錯,但沒有按日期排序。它按數字排序。所以 1-2019 將在 1-2018 之后,而不是 12-2018 之后。
查看完整描述

2 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

您可以使用 pandas 將字符串日期時間轉換為 datetime64 類型。它足夠聰明,可以通過檢查字符串來推斷格式(月優先或日優先)。您可以為其提供一個格式化程序,它可以加速它,這是一個非常大的數據集的限制器。


import pandas as pd


# Make some unsorted dates as strings in a dataframe

df = pd.DataFrame({

    'dates': ['1/19/2019', '1/12/2019', '12/1/2019', '6/7/2019', '7/6/2019']

})


# create a new column that converts the string to a datetime64

df['paidmonth'] = pd.to_datetime(df['dates'])


# sort the data

df.sort_values('paidmonth', inplace=True)

df

答案 2:


好的,如果您只想創建一個單獨的年月列,您可以先將字符串轉換為日期(如第一個答案),然后使用 .dt.period() 將該日期設為年月.


保留完整日期有一些優點,因為您可以使用 pandas 時間序列(按日期時間索引的數據框)方法按月(或季度、日或年...)分組并進行任何類型的聚合,或者甚至是時間序列上的滾動函數。下面的示例按月匯總付款列。


import pandas as pd

import numpy as np


n=400

df = pd.DataFrame({

    'Date': pd.date_range('2018-01-01', periods=n, freq='d'),

    'Payment': np.random.randint(20, 500, n)

})


# Make a column that is only the year and month

df['year-month'] = ts['Date'].dt.to_period('M') 

display(df.head())


# use the full date column to group by month ans sum the payments 

df_bymonth = df.set_index('Date').resample('m').apply({'Payment': 'sum'})

display(df_bymonth.head())

http://img1.sycdn.imooc.com//628c62c800012ba504920622.jpg

查看完整回答
反對 回復 2022-05-24
?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

pandas.to_datetime與 一起使用dt.strftime:


import pandas as pd


df = pd.DataFrame()

df['col1'] = ['%s/19/2019' % i for i in range(1, 10)]

樣本數據:


        col1

0  1/19/2019

1  2/19/2019

2  3/19/2019

3  4/19/2019

4  5/19/2019

5  6/19/2019

6  7/19/2019

7  8/19/2019

8  9/19/2019

使用pd.to_datetime:


df['col2'] = pd.to_datetime(df['col1']).dt.strftime('%Y%m')

print(df)

輸出:


        col1    col2

0  1/19/2019  201901

1  2/19/2019  201902

2  3/19/2019  201903

3  4/19/2019  201904

4  5/19/2019  201905

5  6/19/2019  201906

6  7/19/2019  201907

7  8/19/2019  201908

8  9/19/2019  201909


查看完整回答
反對 回復 2022-05-24
  • 2 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號