Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 726
sheldonzy Avatar asked Apr 27 '26 06:04

sheldonzy


1 Answers

I think better is create list of tuples and then DataFrame constructor:

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'])
like image 50
jezrael Avatar answered Apr 29 '26 20:04

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!