2017-08-03 49 views
0

我需要一个帮助原因我试图通过比较不同的数据帧列来获得一个值。Python:通过比较不同的数据帧列来获得一个值列

首先,我试过使用“for循环”来达到目标​​,但是我有数百万行,所以需要很多时间。 现在,我想用numpy.where,用这种方法:

我有2个数据帧: -df1其中每行都不同于其他(列ID是唯一的主键) - > df1 ['ID','status','boolean'] - df2包含几行,每行都与其他行不同 - > df2 ['code','segment','value']

现在,我需要为dataframe1创建一个名为'weight'的新列。

我想以这种方式来创建栏“权重”:

df1['weight'] = numpy.where(df1['boolean'] == 1, df2[ (df2['code']==df1['ID']) & (df2['segment']==df1['status'])] ['value'], 0) 

列“代码” +“段”是一个独特的密钥,所以它返回一个且只有一个值。

程序执行显示这个错误: “ValueError异常:只能比较相同标记的一系列对象”

谁能帮我明白了吗?

谢谢。

+0

一个时刻,我想给你一些例子... –

回答

1

你可以用左join

像这样的东西可能会奏效做到这一点。如果没有样本数据详细

df_merged = df1.join(df2.set_index(['code', 'segment']), how='left', on=['ID', 'status']) 
df1['weight'] = df_merged['value'].re_index(df1.index).fillna(0) 

set_index()我无法检查,这是需要

on : column name, tuple/list of column names, or array-like 

Column(s) in the caller to join on the index in other, otherwise joins index-on-index. If multiples columns given, the passed DataFrame must have a MultiIndex. Can pass an array as the join key if not already contained in the calling DataFrame. Like an Excel VLOOKUP operation

相关问题