Pandas将列表添加到新列或在末尾追加

问题描述 投票:0回答:1

我将新列表添加到pandas数据框的列中。由于我在循环中执行此操作,因此我想首先创建一个新列并在此列中放入一些值。然后,在其他循环中,我将新值添加到刚刚创建的列。我怎样才能做到这一点?

我有一个名为all_material_percentages的python列表

All Material Percentages:
[0.660377358490566, 0.34285714285714286, ... 1.5151515151515151, 1.12, 0.5892857142857143]
>>> len(all_material_percentages)
48
>>> len(total_parameter_number)
2
>>> len(total_year_number)
2
>>> print(input_material_name)
['Cold Sheet Iron', 'Hot Sheet Iron']  

我的试用期是:

for i in range(total_parameter_number):
    for j in range(total_year_number):        
        output[input_material_name[i]) = pd.Series(all_material_percentages[i*12+(12*j*total_parameter_number):(i*12)+12+(12*j*total_parameter_number)]) 

然后我将输出写入excel文件:excel output

我知道输出(input_material_name [i])被覆盖的问题,但我不知道如何解决这个问题。我试过追加,插入函数,但我找不到办法做到这一点。

python excel pandas
1个回答
0
投票

下面是一个更加pythonic的方式:

import pandas as pd

# first initialize your data frame with the columns
# columns with empty data has been initialized, now you can just add data to it 
df = pd.DataFrame(columns=input_material_name)

# to avoid any confusion I would advise you to first build the list of data for your different columns and at the end just add it to the dataframe

# here 'i' is the index returned by enumerate 
for i, column in enumerate(df.columns):
    for j in range(total_year_number):        
        df[column] = all_material_percentages[i*12+(12*j*total_parameter_number):(i*12)+12+(12*j*total_parameter_number)])

# for writing to excel file
df.to_excel('file.xls')

我希望这有帮助。如果我错过了某些内容或者您想要做一些不同的事情,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.