将列表作为列添加到现有数据框

2024-05-14 00:56:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个数据帧(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])

事先非常感谢 enter image description here


Tags: ofthe数据indataframe原始数据is错误
1条回答
网友
1楼 · 发布于 2024-05-14 00:56:52

使NPQ成为DataFrame,然后将其附加到原始帧,例如:

NPQ_data = NPQ_calculation(NewList)

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

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

注意:根据评论发布答案,以便将问题标记为已解决。仍然是this post的可能副本

相关问题 更多 >