首页 > 解决方案 > 数据帧附加问题:尝试将数据帧一个接一个地附加到 for 循环内的列表中

问题描述

这是 op ,其中月份列中的值必须是 1,2,3,4 但第 4 个月的值会覆盖所有以前的值附加的是我要修改的数据的图像 附加的列表值被for循环的最后一个值覆盖,不确定这里错过了什么尝试了 concat 和 append ,两者都没有给出预期的输出

import pandas as pd
from datetime import datetime as dt

file_name = r"file_path"

df1=pd.read_excel(file_name)
df1.dropna(axis=1, how='all', thresh=20, subset= None, inplace=True)
df1=df1[df1.col1 != "xyz"]
df2=df1.iloc[:,0:1]
df3=df1.iloc[:,2:]

######### first try ######################
## In this try the values in the list were all overwritten by the last 
values from the loop ##

df=pd.DataFrame([])
for i in range(len(df3.columns.values)):
     df4.assign(col1=lambda x: df2.iloc[:,0],
           col2=lambda x: df3.columns[i].year,
           col3=df3.columns[i].month,
           col4=df3.iloc[:,i]) 
     print(df4.head(2))
     df.append(df4)


########### second try #####################
## in this try the list was empty when printed##

df=[]
df4=pd.DataFrame(columns=['col1','col2','col3','col4'])
for i in range(len(df3.columns.values)):
     df4['col1']=df2.iloc[:,0]
     df4['col2']=df3.columns[i].year
     df4['col3']=df3.columns[i].month
     df4['col4']=df3.iloc[:,i]
     df.append(df4)
print(df)

没有错误,预期的结果是该列表应该具有相对于 for 循环的每个迭代值的数据帧 df4 值。

选择的结果是循环中的最后一个值正在覆盖列表的所有元素

标签: pythonpandas

解决方案


for i in range(len(df3.columns.values)):                                                        
    y=1+i
    y=pd.DataFrame(columns=['col1','col2','col3','col4'])
    y['col1']=df2.iloc[:,0]
    y['col2']=df3.columns[i].year
    y['col3']=df3.columns[i].month
    y['col4']=df3.iloc[:,i]
    df.append(y)

推荐阅读