微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将元组拆分为字典中的多列

如何解决如何将元组拆分为字典中的多列

  • 我想得到一个最终的数据帧,其中元组 'key' 被分成两列,分别是 'hr''filename'

  • 我也希望将 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)

这是错误输出

enter image description here

正确输出的示例(为了效率我对其进行了简化):

hr      filename      a      b     c 
8     20191129.0     21.22  0.55  0.45
8     20191129.0      ..     ..    ..
8     20191129.0      ..     ..    ..
14.0  20191129.0      ..     ..    ..

解决方法

  • 将键提取为 k1k2 而不是 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)
  • 或者,keytuple,因为 .groupby 位于多个列上,因此您可以通过调用适当的索引来提取单独的值。
    • 创建 new_row,其中 'hr'key[0]'filename'key[1]
  • 如果 poptlisttuple,那么您可以为 '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 举报,一经查实,本站将立刻删除。