Please find a method to add one line to the Pandas.DataFrame

Asked 2 years ago, Updated 2 years ago, 38 views

You want to create an empty DataFrame and write a code that adds one line at a time. Creating DataFrame succeeded, but when you try to add a row, an error occurs on the string side.

How can I put different types together in one line?

res = DataFrame (columns=('lib', 'qty1', 'qty2') #Successful

res = res.set_value(len(res), 'qty1', 10.0)

python pandas

2022-09-21 16:09

1 Answers

You can use loc to assign.

from pandas import DataFrame
from random import randint


res = DataFrame(columns=('lib', 'qty1', 'qty2'))
for i in range(5):
    res.loc[i] = [randint(-1,1) for n in range(3)]

print(res)

Output:

   lib  qty1  qty2
0   -1     1     0
1    1     0    -1
2    1     1     1
3    1     0     1
4    0     0    -1


2022-09-21 16:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.