简体   繁体   English

Python Pandas将行数据插入一行

[英]Python Pandas insert row data in one line

I have a list messages of messages, when each message in this list, is an object with a 5 items - name, message, action, date, location . 我有一个messages列表,当此列表中的每个消息都是一个具有5个项目的对象- name, message, action, date, location I want to fill my data frame with this information. 我想用此信息填充数据框。

Currently, I'm doing it like the following: 目前,我正在执行以下操作:

j = 1
df = pd.DataFrame(index=range(1, len(messages)+1), columns=['name','message','action','date', 'location'])
for message in messages:

    df.ix[j]['name'] = message.name
    df.ix[j]['message'] = message.message
    df.ix[j]['action'] = message.action
    df.ix[j]['date'] = message.date
    df.ix[j]['location'] = message.location
    j += 1

I feel like indexing is not the best solution I can think of. 我觉得索引并不是我能想到的最佳解决方案。 Any other way to do this? 还有其他方法吗? perhaps without using df.ix[j] a few times. 也许不用df.ix[j]使用df.ix[j]

I think better is create list of tuples and then DataFrame constructor: 我认为更好的方法是创建元组列表,然后创建DataFrame构造函数:

dfs = [(m.name, m.message, m.action, m.date, m.location) for m in messages]

df = pd.DataFrame(dfs, 
                  index=range(1, len(messages)+1), 
                  columns=['name','message','action','date', 'location'])

You can also use nested comprehensions. 您还可以使用嵌套的理解。 This allows you to select attributes / columns centrally. 这使您可以集中选择属性/列。

cols = ['name', 'message', 'action', 'date', 'location']

lst = [tuple(getattr(m, col) for col in cols) for m in messages]

df = pd.DataFrame(lst, index=range(1, len(messages)+1), columns=cols)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM