[英]Python: Keep leading zeroes when converting from excel to CSV with pandas
[英]How to keep leading zeroes from a panda column post operation?
我有一列的數據為:
日期 |
---|
'2021-01-01' |
'2021-01-10' |
'2021-01-09' |
'2021-01-11' |
我只需要將“年和月”作為一列並將其作為 integer 而不是像“2021-01-01”這樣的字符串應該保存為 202101。(我不需要日部分)。
當我嘗試清理數據時,我可以做到,但它會刪除前導零。
df['period'] = df['Date'].str[:4] + df['Date'].str[6:7]
這給了我:
日期 |
---|
20211 |
202110 |
20219 |
202111 |
如您所見,從 1 月到 9 月,它只返回 1 到 9 而不是 01 到 09,這會產生差異。 如果我在合並過程中手動添加一個零,它將使“2021-10”成為 2021010。我希望它只是沒有連字符的年份和月份,並保持前導零幾個月。 請參閱下面我希望它如何出現在新列中。
日期 |
---|
202101 |
202110 |
202109 |
202111 |
我可以使用循環來做到這一點,但這效率不高。 在 python 中是否有更好的方法?
由於對 Python 中切片符號的使用存在誤解,前導零被刪除。
嘗試將您的代碼更改為:
df['period'] = df['Date'].str[:4] + df['Date'].str[5:7]
注意從 [6:7] 到 [5:7] 的變化。
去掉引號,將日期強制轉換為所需格式的日期時間並將其轉換為 integer。 下面的代碼
df['Date_edited']=pd.to_datetime(df['Date'].str.strip("''")).dt.strftime('%Y%m').astype(int)
Date Date_edited
0 '2021-01-01' 202101
1 '2021-01-10' 202101
2 '2021-01-09' 202101
3 '2021-01-11' 202101
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.