pandas数据帧应该嵌套吗?

时间:2015-10-28 05:02:25

标签: python pandas

我正在创建一个python脚本,驱动旧的fortran代码来定位地震。我想将输入参数改为python脚本中的fortran代码,并在数据帧中记录结果以及产生它们的值。每次运行的结果也很方便放入数据帧,导致我有一个嵌套数据帧的情况(IE是一个分配给数据帧元素的数据帧)。例如:

import pandas as pd
import numpy as np

def some_operation(row):
    results = np.random.rand(50, 3) * row['p1'] / row['p2']
    res = pd.DataFrame(results, columns=['foo', 'bar', 'rms'])
    return res

# Init master df
df_master = pd.DataFrame(columns=['p1', 'p2', 'results'], index=range(3))
df_master['p1'] = np.random.rand(len(df_master))
df_master['p2'] = np.random.rand(len(df_master))
df_master = df_master.astype(object) # make sure generic types can be used
# loop over each row, call some_operation and store results DataFrame
for ind, row in df_master.iterrows():
    df_master.loc[ind, "results"] = some_operation(row)

引发了这个例外:

  

ValueError:与DataFrame

不兼容的索引器

然而,如果我将最后一行更改为:

,它会按预期工作
df_master["results"][ind] = some_operation(row) 

我有几个问题:

  1. 为什么切片分配成功时.loc(和.ix)会失败?如果some_operation函数返回了一个列表,字典等,它似乎工作正常。

  2. 应该以这种方式使用DataFrame吗?我知道dtype对象对于排序和其他东西来说可能超慢,但我真的只是使用数据帧一个方便的容器,因为列/索引表示法非常光滑。如果不应该以这种方式使用DataFrames有类似的替代方案吗?我正在查看Panel类,但我不确定它是否适合我的应用程序。我讨厌前进并将上面显示的hack应用到某些代码中,然后在未来的pandas版本中不支持它。

1 个答案:

答案 0 :(得分:1)

  
      
  1. 为什么切片分配成功时.loc(和.ix)会失败?如果some_operation函数返回了一个列表,字典等,它似乎工作正常。
  2.   

这是代码的一个奇怪的小角落案例。它源于以下事实:如果分配的项目是DataFrame,locix则假定您要使用DataFrame的内容填充给定索引。例如:

>>> df1 = pd.DataFrame({'a':[1, 2, 3], 'b':[4, 5, 6]})
>>> df2 = pd.DataFrame({'a':[100], 'b':[200]})
>>> df1.loc[[0], ['a', 'b']] = df2
>>> df1
     a    b
0  100  200
1    2    5
2    3    6

如果此语法允许将DataFrame存储为对象,则不难想象用户的意图不明确的情况,并且模糊不能成为一个好的API。

  
      
  1. 是否应该以这种方式使用DataFrame?
  2.   

只要您知道该方法的性能缺陷(听起来就像您这样做),我认为这是一种非常适合使用DataFrame的方法。例如,我已经看到了一个类似的策略,用于存储经过训练的scikit-learn估计器在一个大的参数网格中进行交叉验证(尽管我现在还记不起这个的确切背景......)