在与其他数据框多个匹配条件之后,将值分配给新的df列

时间:2020-06-19 10:03:43

标签: pandas numpy dataframe assign loc

假设我们有两个数据框:

DF1:

GET /myindex/_msearch
{}
{"query": {"constant_score": {"filter": {"term": {"name.keyword": "Acme Incorporated"}}}}}
{}
{"query": {"bool": {"must": {"match": {"name": "Acme Incorporated"}}, "must_not": {"term": {"name.keyword": "Acme Incorporated"}}}}}

DF2:

spec   u_g    target
G1     4.8    0.88
G2     2.1    0.76
WG2    1.4    0.71
WG2    1.2    0.68
WG2    1.0    0.52
WG3    0.8    0.65
WG3    0.7    0.53
SWG3   0.7    0.31

对于DF2中的每一行,我想查询类型是否与DF1中的条目匹配,如果是,我想查看DF1中是否存在具有对应值u_g_1 == u_g的条目,如果是,请选择目标值并将其分配给DF2。如果不是,则将u_g中相同类型的下一个更大的值分配给新的“目标”列。

DF2_modified:

id  type     u_g_1    
1   WG2      1.4 
2   WG2      1.4
3   WG2      1.0
4   G1       4.8
5   G1       4.9
6   G2       2.1
7   SWG3     0.7
8   WG3      0.8
9   WG3      0.7
10  WG2      1.2
11  nan      0

我尝试过:

id  type     u_g_1   target   
1   WG2      1.4     0.71 
2   WG2      1.4     0.71
3   WG2      1.0     0.52
4   G1       4.8     0.88
5   G1       4.9     0.88
6   G2       2.1     0.76
7   SWG3     0.7     0.31
8   WG3      0.8     0.65
9   WG3      0.7     0.53
10  WG2      1.1     0.68
11  nan      0       nan       

这是行不通的,据我所知,代码也无法处理NaN,这也不会使用u_g的下一个更大的值。

df2['target'] = np.where(df2['type'].isin(df1['spec']), (np.where(df1['u_g_1'].isin(df1['u_g']), df1['g'], 'no value for u_g, therefore no target-value')), 'no specification')

没有给我u_g的最大值

有人可以帮忙吗?

0 个答案:

没有答案