Pandas 替换数据帧中int64末尾的数字

Pandas 替换数据帧中int64末尾的数字,pandas,Pandas,我的dataframe列的格式类似于201902。年为4位,月为2位 我想将YearMonth与MinPurchaseYearMonth进行比较,我将其中的月份替换为01 这是我的代码,与MinPurchaseYearMonth进行比较 tx_merge_mindate.loc[q1['YearMonth']>tx_merge_mindate['MinPurchaseYearMonth'],'UserType'] = 'Existing' 我想将MinPurchaseYearMonth最

我的dataframe列的格式类似于201902。年为4位,月为2位

我想将YearMonth与MinPurchaseYearMonth进行比较,我将其中的月份替换为01

这是我的代码,与MinPurchaseYearMonth进行比较

tx_merge_mindate.loc[q1['YearMonth']>tx_merge_mindate['MinPurchaseYearMonth'],'UserType'] = 'Existing'
我想将MinPurchaseYearMonth最后2位数字替换为01

我想我可以转换为字符串来剪切最后两位数字,但如何在末尾添加01

tx_merge_mindate.loc[q1['YearMonth']>tx_merge_mindate['MinPurchaseYearMonth'].astype(str).str[:-2],'UserType'] = 'Existing'

您可以用数字或
str
slicing来完成。后者可能较慢,但有时可能是一个有用的技巧:

#setup:
df = pd.DataFrame({'date':[201902, 201107, 200011]})
#     date
#0  201902
#1  201107
#2  200011
  • 数字:
  • str
    切片

  • tx_merge_mindate['MinPurchaseYearMonth']-=tx_merge_mindate['MinPurchaseYearMonth']%100-1
    df["date"] -= df["date"] % 100 -1
    #     date
    #0  201901
    #1  201101
    #2  200001
    #dtype: int64
    
    df["date"] = df["date"].astype(str).str[:-2] + "01"
    #     date
    #0  201901
    #1  201101
    #2  200001
    #dtype: object