Python 熊猫:在Dataframe中填充一个新列,其中两个其他列匹配

Python 熊猫:在Dataframe中填充一个新列,其中两个其他列匹配,python,pandas,Python,Pandas,现在我必须对dataframe_1进行计算,然后在dataframe_2上创建一个新列并填充结果。dataframe_one是多索引的,而第二个不是,但有与dataframe_one中的索引匹配的列 这就是我目前正在做的: 作为pd进口熊猫 将numpy作为np导入 dataframe_two = {} dataframe_two['project_id'] = [1, 2] dataframe_two['scenario'] = ['hgh', 'low'] dataframe_two = p

现在我必须对dataframe_1进行计算,然后在dataframe_2上创建一个新列并填充结果。dataframe_one是多索引的,而第二个不是,但有与dataframe_one中的索引匹配的列

这就是我目前正在做的: 作为pd进口熊猫 将numpy作为np导入

dataframe_two = {}
dataframe_two['project_id'] = [1, 2]
dataframe_two['scenario'] = ['hgh', 'low']
dataframe_two = pd.DataFrame(dataframe_two)
dataframe_one = {}
dataframe_one['ts_project_id'] = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
dataframe_one['ts_scenario'] = ['hgh', 'hgh', 'hgh', 'hgh', 'hgh', 'low', 'low', 'low', 'low', 'low']
dataframe_one['ts_economics_atcf'] = [-2, 2, -3, 4, 5 , -6, 3, -3, 4, 5]
dataframe_one = pd.DataFrame(dataframe_one)
dataframe_one.index = [dataframe_one['ts_project_id'], dataframe_one['ts_scenario']]

project_scenario = zip(dataframe_two['project_id'], dataframe_two['scenario'])
dataframe_two['econ_irr'] = np.zeros(len(dataframe_two.index))
i = 0
for project, scenario in project_scenario:
    # Grabs corresponding series from dataframe_one
    atcf = dataframe_one.ix[project].ix[scenario]['ts_economics_atcf']
    irr = np.irr(atcf.values)
    dataframe_two['econ_irr'][i] = irr
    i = i + 1

print dataframe_two
有没有更简单的方法


干杯

如果我理解正确,您需要SQL group_by和聚合函数的等价项。它们本质上是相同的,数据帧的方法和
groupby.SeriesGroupBy
对象的方法

>>> dataframe_one['ts_economics_atcf'].groupby(level=[0,1]).aggregate(np.irr)
ts_project_id  ts_scenario
1              hgh            0.544954
2              low            0.138952
dtype: float64

如果我理解正确,您需要SQL group_by和聚合函数的等价项。它们本质上是相同的,数据帧的方法和
groupby.SeriesGroupBy
对象的方法

>>> dataframe_one['ts_economics_atcf'].groupby(level=[0,1]).aggregate(np.irr)
ts_project_id  ts_scenario
1              hgh            0.544954
2              low            0.138952
dtype: float64

您能否给出一个来自
dataframe\u one
dataframe\u two
(或表示相同问题的类似数据帧)的示例,以及您期望输出的示例?我不确定您所说的“有与dataframe_one中的索引相匹配的列”是什么意思。只是编辑了代码以了解其工作原理。请指出源dataframe(一、二)的内容和预期结果。很难知道您想要的是什么。您能否从
dataframe\u one
dataframe\u two
(或表示相同问题的类似数据帧)中给出一个示例,并举例说明您期望的输出是什么?我不确定您所说的“有与dataframe_one中的索引相匹配的列”是什么意思。只是编辑了代码以了解其工作原理。请指出源dataframe(一、二)的内容和预期结果。很难知道您想要什么。我还需要填写dataframe_2中没有多索引功能的列。我还需要填写dataframe_2中没有多索引功能的列。