简体   繁体   English

将pandas数据框中的整数列转换为前导零的月份

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

I want to change the Month and Day column in the Python pandas dataframe from integer to strings with leading zeros. 我想将Python pandas数据框中的Month and Day列从整数更改为带前导零的字符串。

What I want is here: the input is here as a pandas dataframe: 我想要的是这里:输入在这里作为熊猫数据框:

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

I want to make them like this: 我想让他们像这样:

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

My method is pretty dumb, and it is very slow. 我的方法很笨,而且很慢。

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

Also

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

won't help since to_datetime only has month as integers [1,12] 将无济于事,因为to_datetime仅将月份作为整数[1,12]

I want to change the Month and Day column in the Python pandas dataframe from integer to strings with leading zeros. 我想将Python pandas数据框中的Month and Day列从整数更改为带前导零的字符串。

Use series.str.zfill() : 使用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

You mentioned you wish to have a string value so you can use a simple lambda. 您提到您希望有一个字符串值,以便可以使用简单的lambda。 On the Day example you should have: 在“一天”示例中,您应该具有:

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