Python Pandas:将行值重新用于另一行 - 跨行查找
Python Pandas: reusing row value to another row - lookup across row
我有以下数据框
df1 = DataFrame([['OBJ1', 10, 'BX', 'pool1', 'OBJ2'],['OBJ2', 0, '', '', 'OBJ1'],['OBJ3', 10, 'BY', 'pool2', 'OBJ4'],['OBJ4', 0, '', '', 'OBJ3'],['OBJ5', 10, 'BZ', 'pool3', '']], columns=['OBJ', 'value', 'conf', 'Res', 'Key'])
我想做的是:
- 当值为 0 时检查
- Conf 和 Res 采用与 OBJ 匹配的键的行的值
- 例如OBJ2值为0,key为OBJ 2,则conf应为BX,Res为pool1
我使用查找或其他一些帖子尝试了多种解决方案,但似乎没有任何效果。
df1.loc[df1['value']==0, 'conf'] = df1.loc[df1['OBJ']==df1['Key']]['conf']
失败,因为我意识到这是在寻找具有 OBJ = Key
的行
使用DataFrame.merge
with left_on
and right_on
parameters and index
column created by DataFrame.reset_index
for new DataFrame
, then convert index
column to index
by DataFrame.set_index
and last set new volumns by DataFrame.loc
:
m = df1['value'].eq(0)
cols = ['conf','Res']
df = (df1.reset_index().loc[m, ['index','OBJ']]
.merge(df1, left_on='OBJ', right_on='Key')
.set_index('index')[cols])
print (df)
conf Res
index
1 BX pool1
3 BY pool2
df1.loc[m, cols] = df
print (df1)
OBJ value conf Res Key
0 OBJ1 10 BX pool1 OBJ2
1 OBJ2 0 BX pool1 OBJ1
2 OBJ3 10 BY pool2 OBJ4
3 OBJ4 0 BY pool2 OBJ3
4 OBJ5 10 BZ pool3
我有以下数据框
df1 = DataFrame([['OBJ1', 10, 'BX', 'pool1', 'OBJ2'],['OBJ2', 0, '', '', 'OBJ1'],['OBJ3', 10, 'BY', 'pool2', 'OBJ4'],['OBJ4', 0, '', '', 'OBJ3'],['OBJ5', 10, 'BZ', 'pool3', '']], columns=['OBJ', 'value', 'conf', 'Res', 'Key'])
我想做的是:
- 当值为 0 时检查
- Conf 和 Res 采用与 OBJ 匹配的键的行的值
- 例如OBJ2值为0,key为OBJ 2,则conf应为BX,Res为pool1
我使用查找或其他一些帖子尝试了多种解决方案,但似乎没有任何效果。
df1.loc[df1['value']==0, 'conf'] = df1.loc[df1['OBJ']==df1['Key']]['conf']
失败,因为我意识到这是在寻找具有 OBJ = Key
的行使用DataFrame.merge
with left_on
and right_on
parameters and index
column created by DataFrame.reset_index
for new DataFrame
, then convert index
column to index
by DataFrame.set_index
and last set new volumns by DataFrame.loc
:
m = df1['value'].eq(0)
cols = ['conf','Res']
df = (df1.reset_index().loc[m, ['index','OBJ']]
.merge(df1, left_on='OBJ', right_on='Key')
.set_index('index')[cols])
print (df)
conf Res
index
1 BX pool1
3 BY pool2
df1.loc[m, cols] = df
print (df1)
OBJ value conf Res Key
0 OBJ1 10 BX pool1 OBJ2
1 OBJ2 0 BX pool1 OBJ1
2 OBJ3 10 BY pool2 OBJ4
3 OBJ4 0 BY pool2 OBJ3
4 OBJ5 10 BZ pool3