簡體   English   中英

將pandas數據框中的整數列轉換為前導零的月份

[英]Convert a column of integers in pandas dataframe to month with leading zeros

我想將Python pandas數據框中的Month and Day列從整數更改為帶前導零的字符串。

我想要的是這里:輸入在這里作為熊貓數據框:

Year Month  Day
2018     1    1
2018     1   12
2018     1   18
2018     2    4
2018     2    1
2018     2    2
2018     2   12
2018     3   30

我想讓他們像這樣:

Year Month  Day
2018    01   01
2018    01   12
2018    01   18
2018    02   04
2018    02   01
2018    02   02
2018    02   12
2018    03   30

我的方法很笨,而且很慢。

def Import():
    df = pd.read_csv('Transaction_data.csv',index_col=0)
    n = len(df)
    for i in range(n):
        temp = df['Year'].loc[i]
        df['Year'].loc[i] = str(temp)

    for i in range(n):
        temp = df['Month'].loc[i]
        if temp<10:
            df['Month'].loc[i] = '0'+str(temp)
        else:
            df['Month'].loc[i] = str(temp)

    for i in range(n):
        temp = df['Day'].loc[i]
        if temp<10:
            df['Day'].loc[i] = '0'+str(temp)
        else:
            df['Day'].loc[i] = str(temp)
    return df

pd.to_datetime(df['Month'],format='%d')

將無濟於事,因為to_datetime僅將月份作為整數[1,12]

我想將Python pandas數據框中的Month and Day列從整數更改為帶前導零的字符串。

使用series.str.zfill()

df[['Month','Day']]=df[['Month','Day']].astype(str).apply(lambda x: x.str.zfill(2))
print(df)

   Year Month Day
0  2018    01  01
1  2018    01  12
2  2018    01  18
3  2018    02  04
4  2018    02  01
5  2018    02  02
6  2018    02  12
7  2018    03  30

您提到您希望有一個字符串值,以便可以使用簡單的lambda。 在“一天”示例中,您應該具有:

df['Day'].apply(lambda x: "0"+str(x) if x<10 else x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM