如何解决如何将元组拆分为字典中的多列
-
我也希望将 fit 'a,b,c'= *popt 的输出分成三列 a,c。
-
在当前输出数据框中,最后三列不包含正确的值。它们显示了初始 a、b、c 值,它们是拟合的初始猜测值。他们应该显示拟合的输出(*popt)。
new_df = pd.DataFrame(columns=['hr','filename','a','b','c'])
new_df.columns = ['hr','c']
################### curve fitting ########################################
grouped_df = HL.groupby(["hr","filename"]) ## this is my initial dataframe
for key,g in grouped_df:
a = g['NPQ'].max()
b = g['NPQ'].min()
c = 0.36
popt,pcov = curve_fit(model,g['time'],g['NPQ'],p0 = np.array([a,c]),absolute_sigma=True)
print('Estimated parameters: \n',popt))
##################### new data frame
new_row = {'hr': key,'a':a,'b':b,'c':c }
new_df = new_df.append(new_row,ignore_index=True)
print(new_df)
正确输出的示例(为了效率我对其进行了简化):
hr filename a b c
8 20191129.0 21.22 0.55 0.45
8 20191129.0 .. .. ..
8 20191129.0 .. .. ..
14.0 20191129.0 .. .. ..
解决方法
- 将键提取为
k1
和k2
而不是key
,因为您对两列执行.groupby
。 - 然后创建
new_row
,其中'hr'
为k1
,'filename'
为k2
- 您可以将返回值分配给
popt
,而不是将它们分配给(x,y,z)
。
for (k1,k2),g in df.groupby(["hr","filename"]):
...
(x,z),pcov = curve_fit(model,g['time'],g['NPQ'],p0=np.array([a,b,c]),absolute_sigma=True)
...
new_row = {'hr': k1,'filename': k2,'a': x,'b': y,'c': z}
new_df = new_df.append(new_row,ignore_index=True)
- 或者,
key
是tuple
,因为.groupby
位于多个列上,因此您可以通过调用适当的索引来提取单独的值。- 创建
new_row
,其中'hr'
为key[0]
,'filename'
为key[1]
- 创建
- 如果
popt
是list
或tuple
,那么您可以为'a'
、'b'
和'c'
分配适当的索引。
for key,"filename"]):
...
popt,p0 = np.array([a,absolute_sigma=True)
...
new_row = {'hr': key[0],'filename': key[1],'a': popt[0],'b': popt[1],'c': popt[2]}
new_df = new_df.append(new_row,ignore_index=True)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。