我试图在不同的集合中匹配多个列,并用所有不匹配的列名更新另一列,
用不匹配的列名更新结果列
输入:
A B C D E
0 f e b a d
1 c b a c b
2 f f a b c
3 d c c d c
4 f b b b e
5 b a f c d预期输出
A B C D E MATCHES
0 f e b a d AD, BC Unmatched
1 c b a c b BC Unmatched
2 f f a b c AD, BC Unmatched
3 d c c d c ALL MATCHED
4 f b b b e AD Unmatched
5 b a f c d AD, BC Unmatched下面的代码在函数内部使用时会出现错误,否则,如果我单独使用而不使用任何函数,它的工作情况很好。
def test(x):
try:
for idx in df.index:
unmatch_list = []
if not df.loc[idx, 'A'] == df.loc[idx, 'D']:
unmatch_list.append('AD')
if not df.loc[idx, 'B'] == df.loc[idx, 'C']:
unmatch_list.append('BC')
# etcetera...
if len(unmatch_list):
unmatch_string = ', '.join(unmatch_list) + ' Unmatched'
else:
unmatch_string = 'ALL MATCHED'
df.loc[idx, 'MATCHES'] = unmatch_string
except ValueError:它在尝试处理时会产生错误:
if not df.loc[idx, 'A'] == df.loc[idx, 'D']:
Error: pandas.core.indexing.IndexingError: Too many indexers需要建议:
发布于 2021-05-18 05:06:15
怎么叫函数?
对于我来说,如果添加return df并将DataFrame传递给函数,那么我就可以工作了:
def test(x):
try:
for idx in df.index:
unmatch_list = []
if not df.loc[idx, 'A'] == df.loc[idx, 'D']:
unmatch_list.append('AD')
if not df.loc[idx, 'B'] == df.loc[idx, 'C']:
unmatch_list.append('BC')
# etcetera...
if len(unmatch_list):
unmatch_string = ', '.join(unmatch_list) + ' Unmatched'
else:
unmatch_string = 'ALL MATCHED'
df.loc[idx, 'MATCHES'] = unmatch_string
except ValueError:
print ('error')
return df
df = test(df)
print (df)
A B C D E MATCHES
0 f e b a d AD, BC Unmatched
1 c b a c b BC Unmatched
2 f f a b c AD, BC Unmatched
3 d c c d c ALL MATCHED
4 f b b b e AD Unmatched
5 b a f c d AD, BC Unmatched使用apply解决方案是可能的,但必要的更改功能如下:
def test(x):
try:
unmatch_list = []
if not x['A'] == x['D']:
unmatch_list.append('AD')
if not x['B'] == x['C']:
unmatch_list.append('BC')
# etcetera...
if len(unmatch_list):
unmatch_string = ', '.join(unmatch_list) + ' Unmatched'
else:
unmatch_string = 'ALL MATCHED'
except ValueError:
print ('error')
return unmatch_string
df['MATCHES'] = df.apply(test, axis=1)
print (df)
A B C D E MATCHES
0 f e b a d AD, BC Unmatched
1 c b a c b BC Unmatched
2 f f a b c AD, BC Unmatched
3 d c c d c ALL MATCHED
4 f b b b e AD Unmatched
5 b a f c d AD, BC Unmatchedhttps://stackoverflow.com/questions/67580225
复制相似问题