首页 > 解决方案 > 根据数据框中许多其他列的值在列中分配值

问题描述

我有一个包含 5 列的数据框,我想根据其他 4 列更新一列,数据框看起来像这样

from       via      to       x       y 
 3          2       13      in       out
 3          2       15      in       out
 3          2       21      in       out
13          2       3             
15          2       13     
21          2       13
1          12        2 
1          12        2
1          12        22
2          12        1      in
2          12        22     in      out
22         12        2    

这个想法是根据其他四列的值填充 X 列,顺序应该是这样的:我必须检查 x 和 y 是否有值,如果是,那么我必须使用 (from , via) 并将所有行中的值与 (to, via) 的值进行比较(如果它们相同),因此我必须将对应于 (from, via) 的 Y 的值分配给具有(to, via) 的值相等,所以在这个例子中,我可以看到 (from=3, Via=2 有 x 和 y 值,所以我将取 (from=3, Via=2) 的值并比较它在所有行中使用 (to, via) 的值,然后我可以在具有 (to=3, via=10) 的行中分配 (y=out) 的值

最终结果应该是这样的:

from       via      to       x       y 
 3          2       13      in       out
 3          2       15      in       out
 3          2       21      in      
13          2       3       out      
15          2       13      out
21          2       13
1          12        2      out 
1          12        2      out
1          12        22     out
2          12        1      in
2          12        22     in      out
22         12        2      out

我怎么能在熊猫数据框中做到这一点?

标签: pythonpandasdataframemultiple-columns

解决方案


我找不到完全相同的结果,但我使用了描述的算法:

# identify the lines where a change will occur and store the index and the new  value
tmp = df.assign(origix=df.index).merge(df[~df['x'].isna() & ~df['y'].isna()], 
                                       left_on = ['from', 'via'], right_on = ['to', 'via'],
                                       suffixes=('_x', '')).set_index('origix')

# apply changes in dataframe:
df.loc[tmp.index, 'x'] = tmp['y']

它给:


推荐阅读