csv Pandas中的前置数据

acruukt9  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(66)

我正在做一个网站,将允许您在Twitter上其他的消息。每条消息都将在csv文件中包含其tweet。我将遍历csv文件,找到给定消息的所有tweet,并将它们排列成一个列表。
问题是,当我循环数据时,最早的tweet(文件最开始的tweet)将首先出现在列表中。有没有一种方法可以从下到上遍历pandas DataFrame,或者在追加tweet时将它们追加到文件的开头?下面是我的代码:

current_message_name = 'Draft Message' # This is the name of the message the user is veiwing right now.

tweets = []
df = pd.read_csv('data/tweets.csv')

for index, row in df.iterrows():
    tweets.append({
    'poster':f'{row["poster"]}',
    'date':f'{row["date"]}',
    'message':f'{row["message"]}',
 })
nafvub8i

nafvub8i1#

尽量不要循环使用pandas。(ref:Does pandas iterrows have performance issues?
如果需要字典列表,请使用to_dict

tweets = df.iloc[::-1][['poster', 'date', 'message']].to_dict(orient='records')
ubbxdtey

ubbxdtey2#

以下是你如何处理它:

current_message_name = 'Draft Message'
tweets = []
df = pd.read_csv('data/tweets.csv')

# Reversing the DataFrame
df = df.iloc[::-1]

for index, row in df.iterrows():
    tweets.append({
        'poster':f'{row["poster"]}',
        'date':f'{row["date"]}',
        'message':f'{row["message"]}',
    })

相关问题