我有几个数据框在某些列中混合了这种ASP.NET格式的日期“/ Date(1239018869048)/”。我已经想出如何将它解析为python的给定列的日期时间格式。但是,我想将此逻辑放入一个函数中,以便我可以将任何数据帧传递给它,并使用pd.Dataframe.replace替换它找到的匹配正则表达式的所有日期。
就像是:
def pretty_dates():
#Messy logic here
df.replace(to_replace=r'\/Date(d+)', value=pretty_dates(df), regex=True)
问题在于,传递给pretty_dates的df是整个数据帧,而不仅仅是需要替换的单元格。
所以我想弄清楚的概念是,如果有一种方法,当使用df.replace时应该替换的值可以是函数而不是静态值。
非常感谢你提前
编辑为了尝试添加一些清晰度,我在数据框中有许多列,超过一百个包含此日期格式的列。我不想列出每个有日期的列。有没有办法在我的数据集中的所有列中应用清除我的日期的函数?所以我不想清理1列,而是清理数据帧的所有数百列。
我确信你可以使用正则表达式一步完成,但这里是如何立即将它应用于整个列:
df = pd.Series(['/Date(1239018869048)/',
'/Date(1239018869048)/'],dtype=str)
df = df.str.replace('\/Date\(', '')
df = df.str.replace('\)\/', '')
print(df)
0 1239018869048
1 1239018869048
dtype: object
据我所知,您需要将自定义函数应用于指定列中的选定单元格。希望,以下示例可以帮助您:
import pandas as pd
df = pd.DataFrame({'x': ['one', 'two', 'three']})
selection = df.x.str.contains('t', regex=True) # put your regexp here
df.loc[selection, 'x'] = df.loc[selection, 'x'].map(lambda x: x+x) # do some logic instead
您可以在循环中将此过程应用于df的所有列:
for col in df.columns:
selection = df.loc[:, col].str.contains('t', regex=True) # put your regexp here
df.loc[selection, col] = df.loc[selection, col].map(lambda x: x+x) # do some logic instead