【发布时间】:2023-01-03 20:57:19
【问题描述】:
我想知道是否有更好的解决方案来保留不同的值(以便轻松捕获它们)并删除某些列下的相同值。
merged = pd.merge(us_df, gb_df, how='outer', indicator=True)
res = pd.merge(merged[merged['_merge'] == 'left_only'].drop('_merge', axis=1),
merged[merged['_merge'] == 'right_only'].drop('_merge', axis=1),
on=us_df.columns.tolist()[0:col_range],
how='outer',
suffixes=('_US', '_GB')).fillna(' ')
cols = [col for col in res.columns.tolist() if '_US' in col or '_GB' in col]
sorted_cols = [col for col in res.columns.tolist() if '_US' not in col and '_GB' not in col] + sorted(cols)
我得到这张桌子(资源):
| Id | ages_GB | ages_US | salary_GB | salary_US |
|---|---|---|---|---|
| 6 | 45 | 45 | 34 | 67 |
| 43 | 12 | 11 | 65 | 65 |
到目前为止,我使用了这个迭代:
cols = [ages_US, salary_US, ages_GB, salary_GB]
for i, row in res.iterrows():
for us, gb in zip(cols[:len(cols) // 2], cols[len(cols) // 2:]):
if row[us] == row[gb]:
res.at[i, us] = res.at[i, gb] = ' '
得到结果(其中列下的相同值列替换为“”(空格)):
| Id | ages_GB | ages_US | salary_GB | salary_US |
|---|---|---|---|---|
| 6 | 34 | 67 | ||
| 43 | 12 | 11 |
是否有另一种方法可以得到类似的结果?
【问题讨论】:
标签: pandas dataframe html-table