python - 根据数据框中许多其他列的值在列中分配值
问题描述
我有一个包含 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
我怎么能在熊猫数据框中做到这一点?
解决方案
我找不到完全相同的结果,但我使用了描述的算法:
# 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']
它给:
推荐阅读
- java - 如何在spring boot中重写java.sql.Array Descriptor和java.sql.ARRAY?
- java - 有人可以举一些关于 TypeIdentifier 的例子吗?
- express - 如何使用 expressjs vhost 功能运行多个 nuxt 实例
- javascript - Google Script for loop 每次调用时都会运行整个数组 - 寻找
- excel - VBA代码后无法再访问我的excel工作簿
- javascript - 我可以使用什么 vanilla javascript api 来确定图像是否已完成加载?
- android-studio - java.lang.NumberFormatException:对于输入字符串:“文件名”,同时从文件管理器中选择文件。安卓工作室
- python - 抓取数据推特时语法无效?
- android - 限制 Flutter 中特定用户的 FCM 通知
- python - 试图用python矩阵中的索引切片来理解语法