簡體   English   中英

根據條件替換 pandas dataframe 列中的 int 或字符串的一部分

[英]replace part of an int or string in a pandas dataframe column upon condition

我有一個 pandas dataframe,其中有一列表示日期但以 int 格式保存。 對於幾個日期,我有第 13 個月和第 14 個月。 我想用第 12 個月替換第 13 個月和第 14 個月。 然后,最終將其轉換為 date_time 格式。

Original_date
20190101
20191301
20191401

New_date
20190101
20191201
20191201

我嘗試將格式替換為字符串,然后僅根據字符串 [4:6] 中的月份索引進行替換,但沒有成功:

df.original_date.astype(str)
for string in df['original_date']:
    if string[4:6]=="13" or string[4:6]=="14":
        string.replace(string, string[:4]+ "12" + string[6:])
print(df['original_date'])

您可以將.str.replace與正則表達式一起使用

df['New_date'] = df['Original_date'].astype(str).str.replace('(\d{4})(13|14)(\d{2})', r'\g<1>12\3', regex=True)
print(df)

   Original_date  New_date
0       20190101  20190101
1       20191301  20191201
2       20191401  20191201

為什么不直接寫一個正則表達式呢?

s = pd.Series('''20190101
20191301
20191401'''.split('\n')).astype(str)
s.str.replace('(?<=\d{4})(13|14)(?=01)', '12', regex=True)

產量:

0    20190101
1    20191201
2    20191201
dtype: object

(注意,您需要將 output 重新分配回列以將其保留在 memory 中。)

您可以在單獨的 function 中編寫替換和邏輯,如果您還需要更改年份或月份,這還可以讓您輕松調整它。 apply允許您在 DataFrame 的每一行上使用 function。

import pandas as pd

def split_and_replace(x):
    year = x[0:4]
    month = x[4:6]
    day = x[6:8]
    if month in ('13', '14'):
        month = '12'
    else:
        pass
    
    return year + month + day
    

df = pd.DataFrame(
    data={
        'Original_date': ['20190101', '20191301', '20191401']    
    }
)

res = df.Original_date.apply(lambda x: split_and_replace(x))

print(res)

暫無
暫無

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

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