首页 > 解决方案 > 将列表作为列添加到现有数据框

问题描述

我使用数据框(NewList)来计算变量(NPQ),然后我想将此变量(这是一个列表)保存到原始数据框中的一列中。我得到一个错误。

def NPQ_calculation(NewList):      #this is the dataframe      
   Fm_prime = NewList.iloc[0:7, 1] #2nd column in dataframe
   NPQ = []
   NPQ.append(Fm/Fm_prime - 1)     #Fm is the 4th column in dataframe
   return NPQ                      # this is the variable I want to add

# call function for NPQ calculation
NPQ = NPQ_calculation(NewList)
###PROBLEM 
NewList['NPQ']= NPQ

这是我收到的错误消息:

ValueError: Length of values does not match length of index

这是我想添加新列(NPQ)的原始数据框[![我使用第 2 列和第 4 列来计算 NPQ,并希望将结果添加到最后一列][2] ][2])

非常感谢您提前 在此处输入图像描述

标签: pythonlistfunctiondataframe

解决方案


制作NPQ一个DataFrame然后将其附加到原始框架,例如:

NPQ_data = NPQ_calculation(NewList)

NPQ_df = pd.DataFrame({'NPQ': NPQ_DATA})

NewList = pd.concat([NewList, NPQ_df], axis=1)

注意:发布评论中的答案,以便可以将问题标记为已解决。仍然可能是这篇文章的副本。


推荐阅读