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

2024-05-14 09:04:38 发布

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

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

  • 我还希望fit'a,b,c'=*popt的输出被分成三列a,b,c

  • 在当前输出数据帧中,最后三列不包含正确的值。它们显示初始a、b、c值,这是拟合的初始猜测。它们应该显示拟合(*popt)的输出

我附上我的代码、当前错误的输出和正确的输出示例。先谢谢你

new_df = pd.DataFrame(columns=['hr', 'filename', 'a', 'b','c'])
new_df.columns = ['hr', 'filename', 'a', 'b','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, b, 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      ..     ..    ..

Tags: columns数据keytrue示例dfnew错误
1条回答
网友
1楼 · 发布于 2024-05-14 09:04:38
  • 将键提取为k1k2,而不是key,因为您在两列上执行.groupby
  • 然后创建new_row,其中'hr'k1,而'filename'k2
  • 您可以将返回值分配给(x, y, z),而不是将返回值分配给popt
for (k1, k2), g in df.groupby(["hr", "filename"]):
    ...
    (x, y, 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位于多个列上,所以可以通过调用适当的索引来提取单独的值。
    • 用{}作为{}和{}作为{}创建{}
  • 如果poptlisttuple,则可以将适当的索引分配给'a''b''c'
for key, g in df.groupby(["hr", "filename"]):
    ...
    popt, pcov = curve_fit(model, g['time'], g['NPQ'], p0 = np.array([a, b, c]), 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)

相关问题 更多 >

    热门问题