【问题标题】:Updating Each Row with Minutes Since First Row用自第一行以来的分钟数更新每一行
【发布时间】:2017-02-12 02:15:17
【问题描述】:

我有一个包含一百万条推文的文件。第一条推文发生在2013-04-15 20:17:18 UTC。我想用自minsSince 第一条推文以来的分钟数更新每条推文行。

我找到了有关日期时间 here 和转换时间 here 的帮助,但是当我将两者放在一起时,我没有得到正确的时间。它可能是每个 published_at 值末尾的 UTC 字符串。

它抛出的错误是:

tweets['minsSince'] = tweets.apply(timesince,axis=1)
...
TypeError: ('string indices must be integers, not str', u'occurred at index 0')

感谢您的帮助。

#Import stuff
from datetime import datetime
import time
import pandas as pd
from pandas import DataFrame

#Read the csv file
tweets = pd.read_csv('BostonTWEETS.csv')
tweets.head()

#The first tweet's published_at time
starttime = datetime (2013, 04, 15, 20, 17, 18)

#Run through the document and calculate the minutes since the first tweet
def timesince(row):
    minsSince = int()
    tweetTime = row['published_at']
    ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweetTime['published_at'], '%Y-%m-%d %H:%M:%S %UTC'))
    timediff = (tweetTime - starttime)
    minsSince.append("timediff")
    return ",".join(minsSince)

tweets['minsSince'] = tweets.apply(timesince,axis=1)

df = DataFrame(tweets)

print(df)

前 5 行的示例 csv file

【问题讨论】:

  • 你能提供你的 csv 样本吗?
  • 我在上面的描述中提供了一个示例 csv 文件。谢谢

标签: python datetime twitter time


【解决方案1】:
#Import stuff
from datetime import datetime
import time
import pandas as pd
from pandas import DataFrame

#Read the csv file
tweets = pd.read_csv('sample.csv')
tweets.head()

#The first tweet's published_at time
starttime = tweets.published_at.values[0]
starttime = datetime.strptime(starttime, '%Y-%m-%d %H:%M:%S UTC')

#Run through the document and calculate the minutes since the first tweet
def timesince(row):
    ts = datetime.strptime(row, '%Y-%m-%d %H:%M:%S UTC')
    timediff = (ts- starttime)
    timediff = divmod(timediff.days * 86400 + timediff.seconds, 60)
    return timediff[0]

tweets['minSince'] = 0
tweets.minSince = tweets.published_at.map(timesince)

df = DataFrame(tweets)

print(df)

我希望这是您正在寻找的。

【讨论】:

  • 我得到了错误AttributeError: 'DataFrame' object has no attribute 'minsSince'
  • 您的 csv 没有 minsSince 作为标题,请使用 tweets.published_at .. 这是您正在处理的列..
  • 谢谢,这很好用。我非常感谢您的帮助
  • 我有一个后续问题。我现在想在几秒钟内得到答案,而不是几分钟后。我试过timediff = (timediff.days * 86400 + timediff.seconds),但我得到了int object has no attribute
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
相关资源
最近更新 更多