简体   繁体   中英

How to add rows to data frame of two lists

I have two create a CSV for 2 lists. So I converted them to data frames and tried appending them but 2nd row keeps overwriting instead of adding it into a new row. The 'Time' keeps incrementing by 1. Can you please help me.

import pandas as pd
sensor_keys1 = open("sensor_keys1.csv", "w")
a = ['Time', 'sensor_Mtr_-12', 'sensor_Mtr_-12']
b= ['0', '1.2','1.3']
my_df1 = pd.DataFrame([a])
for i in range(0, 10):
    my_df2 =  pd.DataFrame([b])
    sensor_keys1=my_df1.append(my_df2)
    sensor_keys1.to_csv("new_sensor_keys1.csv", index=False)

maybe try to set the column names using the columns argument in pd.DataFrame() :

sensor_keys1 = open("sensor_keys1.csv", "w")
a = ['Time', 'sensor_Mtr_-12', 'sensor_Mtr_-12']
b= ['0', '1.2','1.3']

df = pandas.DataFrame([b], columns=a)

The Time incrementing by one indicates that it is set as index or you are confusing it with the index (cannot tell from your example as no sample output is given)

# append to the dataframe in the loop 
# (not most efficient way but can't tell from your example what you try to achieve)
for i in range(10):
    sensor_keys1 = sensor_keys1.append(df)

#save the df to csv file
sensor_keys1.to_csv("new_sensor_keys1.csv", index=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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