I can't add data successfully in pandas.

Asked 2 years ago, Updated 2 years ago, 45 views

I'd like to add data on Pandas, but I don't know what to do.
I thought it could be done with append, but the data I want to include in the data specified in the column is not included.
0 is the label name, and Pandas will line up the data vertically.
I would like to include a list in the label name specified in columns.
The order of lists and columns is the same.

data_set_list=[10,1,2]
a=pd.DataFrame(columns=["V", "I", "1"])
a.append(data_set_inst)

I think it's better to put the data frame directly instead of preparing it empty, but
In the actual code, I would like to add additional data to the list, so I would like to be able to add it.

Additional information

data_set_list=[ ]

data_set_list.append(x)  

df = pd.DataFrame(data_set_list,
                  columns=['V', 'I', '1'])

The append part will be repeated in the for statement, but
Do you like this feeling?

python pandas

2022-09-30 20:18

2 Answers

How to convert to a dictionary (dict) and add it

import pandas as pd

data_set_list = [10,1,2]
a=pd.DataFrame(columns=["V", "I", "1"])
for_in range (1000):
    a=a.append(dict(zip(a.columns,data_set_list))), ignore_index=True)

display(a)

(Just in case)
If you add data one by one in Pandas, it will be slow, so
If possible, it may be better to store data in list or dict (last batch conversion to DataFrame)

To save with list

data_set_list=[ ]
for n in range (1000):
    data_set_list.append([10,n,2])

df = pd.DataFrame(data_set_list,
                  columns=['V', 'I', '1'])
df
#       VI1
#  0    10  0   2
#  1    10  1   2
#  2    10  2   2
#  3    10  3   2
#  4    10  4   2
#...    ... ... ...
#995    10  995 2
#996    10  996 2
#997    10  997 2
#998    10  998 2
#999    10  999 2
# 3 columns of 1000 rows


2022-09-30 20:18

You can add rows by converting the list to Series.

import pandas as pd

data_set_list = [10,1,2]
a=pd.DataFrame(columns=["V", "I", "1"])
series=pd.Series(data_set_list, index=a.columns)
a. append(series, ignore_index=True)
print(a)

#    VI1
#0  10  1  2

Reference:
Find out how to add one line at a time to pandas.DataFrame
Add columns and rows to pandas.DataFrame (assign, append, etc.)


2022-09-30 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.