【发布时间】:2022-01-16 06:22:26
【问题描述】:
我有一个如下的数据框:
import pandas as pd
data = {'name': ['the weather is good', ' we need fresh air','today is sunny', 'we are lucky'],
'name_1': ['we are lucky','the weather is good', ' we need fresh air','today is sunny'],
'name_2': ['the weather is good', 'today is sunny', 'we are lucky',' we need fresh air'],
'name_3': [ 'today is sunny','the weather is good',' we need fresh air', 'we are lucky']}
df = pd.DataFrame(data)
我想逐行比较列(意味着要比较具有相同索引的行),如果重复项与第一列具有相同的值,则用“相同”一词替换它们。我想要的输出是:
name name_1 name_2 \
0 the weather is good we are lucky same
1 we need fresh air the weather is good today is sunny
2 today is sunny we need fresh air we are lucky
3 we are lucky today is sunny we need fresh air
name_3
0 today is sunny
1 the weather is good
2 we need fresh air
3 same
为了找到这些值,我尝试了以下方法:
import numpy as np
np.where(df['name'].eq(df['name_1'])|df['name'].eq(df['name_2'])|df['name'].eq(df['name_3']))
但要替换它们,我不知道如何为 np.where() 制定(条件,x,y)。以下对于列 'name' 和 'name_3' 的返回相同:
np.where(df['name'].eq(df['name_1'])|df['name'].eq(df['name_2'])|df['name'].eq(df['name_3']),'same',df)
【问题讨论】:
-
ch1、ch2和ch3是什么?
标签: python pandas replace compare rowwise