【问题标题】:Most efficient way to loop through and update rows in a large pandas dataframe在大熊猫数据框中循环和更新行的最有效方法
【发布时间】:2019-02-22 02:20:20
【问题描述】:

这是我更新数据框行的代码:

def arrangeData(df):
hour_from_timestamp_list = []
date_from_timestamp_list = []
for row in df.itertuples():
    timestamp = row.timestamp
    hour_from_timestamp = datetime.fromtimestamp(
        int(timestamp) / 1000).strftime('%H:%M:%S')
    date_from_timestamp = datetime.fromtimestamp(
        int(timestamp) / 1000).strftime('%d-%m-%Y')
    hour_from_timestamp_list.append(hour_from_timestamp)
    date_from_timestamp_list.append(date_from_timestamp)
df['Time'] = hour_from_timestamp_list
df['Hour'] = pd.to_datetime(df['Time']).dt.hour
df['ChatDate'] = date_from_timestamp_list
return df

我试图从时间戳中提取时间、小时和聊天日期。代码工作正常。但是当存在大量数据时,大约 300,000 行,该函数非常慢。谁能建议一种更好的方法来更快地执行此功能?

对于循环,我尝试了更慢的 iterrows()。

这是我正在处理的文件:

{
"_id" : ObjectId("5b9feadc32214d2b504ea6e1"),
"id" : 34176,
"timestamp" : NumberLong(1535019434998),
"platform" : "Email",
"sessionId" : LUUID("08a5caac-baa3-11e8-a508-106530216ef0"),
"intentStatus" : "NotHandled",
"botId" : "tony"
}

【问题讨论】:

  • 你能添加一些数据样本吗?
  • @jezrael 用数据样本编辑了问题

标签: python pandas loops dataframe


【解决方案1】:

我相信这里可以使用:

#thanks @Chris A for another solution
t = pd.to_datetime(df['timestamp'], unit='ms')

t = pd.to_datetime(df['timestamp'].astype(int) / 1000)
#alternative
#t = pd.to_datetime(df['timestamp'].apply(int) / 1000)
#t = pd.to_datetime([int(x) / 1000 for x in df['timestamp']] )

df['Time'] = t.dt.strftime('%H:%M:%S')
df['Hour'] = t.dt.hour
df['ChatDate'] = t.dt.strftime('%d-%m-%Y')

【讨论】:

  • @jezrael,您的代码运行良好,而且比循环快得多。还有一件事,我得到了 GMT 的时间戳,我怎样才能在我的当地时间 GMT +05:30 得到它?有没有办法做到这一点?
猜你喜欢
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2011-12-11
  • 2021-08-31
相关资源
最近更新 更多