4 回答

TA貢獻1936條經驗 獲得超7個贊
使用更全面的正則表達式:
from itertools import groupby
import re
for k, cols in groupby(sorted(df.columns), lambda x: x[:-2] if re.match(".+_(1|2)$", x) else None):
cols=list(cols)
if(len(cols)==2 and k):
df[f"{k}_check"]=df[cols[0]].eq(df[cols[1]])
它將僅將名稱以和名稱結尾的列配對在一起,而不管您之前在其名稱中有什么,僅當有2-和(假設您沒有2列具有相同名稱)時才計算。_1_2_check_1_2
對于示例數據:
A_1 A_2 B_1 B_2 A_check B_check
0 charlie charlie beta cappa True False
1 charlie charlie beta delta True False
2 charlie charlie beta beta True True

TA貢獻1982條經驗 獲得超2個贊
如果您知道列名稱的第一部分,則可以使用wide_to_long,即...:A,B
(pd.wide_to_long(df.reset_index(), ['A','B'], 'index','part',sep='_')
.groupby('index').nunique().eq(1)
.add_suffix('_check')
)
輸出:
A_check B_check
index
0 True False
1 True False
2 True True

TA貢獻1796條經驗 獲得超7個贊
您可以拆分列并按拆分結果的第一個值的序列進行分組,并調用以進行比較axis=1agg
i_cols = df.columns.str.split('_')
df_check = (df.groupby(i_cols.str[0], axis=1).agg(lambda x: x.iloc[:,0] == x.iloc[:,-1])
.add_suffix('_check'))
In [69]: df_check
Out[69]:
A_check B_check
0 True False
1 True False
2 True True

TA貢獻1858條經驗 獲得超8個贊
另一種方法是使用 pd 使用數據幀重整。多索引:
df = pd.DataFrame([['charlie', 'charlie', 'beta', 'cappa'],
['charlie', 'charlie', 'beta', 'delta'],
['charlie', 'charlie', 'beta', 'beta']],
columns=['A_1', 'A_2','B_1','B_2'])
df.columns = df.columns.str.split('_', expand=True) #Creates MultiIndex column header
dfs = df.stack(0) #move the 'A' and 'B' and any others to rows
df_out = (dfs == dfs.shift(-1, axis=1))['1'].unstack() #Compare column 1 to column 2 and move 'A's and 'B's back to columns.
print(df_out)
輸出:
A B
0 True False
1 True False
2 True True
添加回答
舉報