我有一个df,它在‘生命周期间隔’列中有3个唯一的值。它的时间间隔为4-11个月,但原始导入的df将其识别为datetime.datetime,返回一个长而烦人的日期格式值。我已经包括了一张图片,我尝试的代码和预期的输出:
尝试代码:
df['Lifecycle Interval'].replace(datetime.datetime(2022, 4, 11, 0, 0), '4-11', inplace=True)
或者:
df['Lifecycle Interval'].replace('2022-04-11 00:00:00', '4-11', inplace=True)
预期产出:
df = pd.DataFrame({'Lifecycle Interval':['0-3', '4-11', '12+']})
df['Lifecycle Interval'].unique()
发布于 2022-08-30 00:02:46
如果它是日期时间,则可以应用一个函数将其转换为所需的格式,否则返回现有的值。
import pandas as pd
import datetime
df = pd.DataFrame({'Lifecycle Interval':['0-3',datetime.datetime(2022,4,11,0,0),'12+']})
df['Lifecycle Interval'] = df['Lifecycle Interval'].apply(lambda x: x.strftime('%#m-%#d') if isinstance(x, datetime.datetime) else x)
输出
Lifecycle Interval
0 0-3
1 4-11
2 12+
https://stackoverflow.com/questions/73535722
复制相似问题