基于Kids/Teen列替换DataFrame中'together'值的实现求助
解决方案
先确认你的原始数据构造代码(表格里的Column A对应代码中的col_1):
import pandas as pd import numpy as np data = {'col_1': ['together', 'married', 'single', 'together'], 'kids': [1, 0, 0, 0], 'teen': [1, 1, 0, 0] } df = pd.DataFrame.from_dict(data)
以下是三种实现方式,按需选择:
方法1:用np.where高效处理(推荐)
利用numpy的where函数结合复合条件一次性完成替换,效率最高,适合大规模数据:
df['col_1'] = np.where( df['col_1'] == 'together', np.where((df['kids'] == 0) & (df['teen'] == 0), 'single', 'married'), df['col_1'] # 非'together'的行保留原内容 )
方法2:用apply函数实现(符合你的尝试方向)
通过apply逐行处理,逻辑直观,便于理解:
def replace_together(row): if row['col_1'] != 'together': return row['col_1'] if row['kids'] == 0 and row['teen'] == 0: return 'single' else: return 'married' df['col_1'] = df.apply(replace_together, axis=1)
也可以用lambda简化为一行:
df['col_1'] = df.apply( lambda x: 'single' if (x['col_1'] == 'together' and x['kids'] == 0 and x['teen'] == 0) else ('married' if x['col_1'] == 'together' else x['col_1']), axis=1 )
方法3:用loc布尔索引分步替换
分步操作逻辑清晰,容易调试:
# 替换kids和teen均为0的'together'为single df.loc[(df['col_1'] == 'together') & (df['kids'] == 0) & (df['teen'] == 0), 'col_1'] = 'single' # 替换剩余的'together'为married(剩余行满足kids/teen至少一个为1) df.loc[df['col_1'] == 'together', 'col_1'] = 'married'
执行任意一种方法后,最终DataFrame结果如下:
| col_1 | kids | teen |
|---|---|---|
| married | 1 | 1 |
| married | 0 | 1 |
| single | 0 | 0 |
| single | 0 | 0 |
内容的提问来源于stack exchange,提问作者VeeA
相关产品推荐
相关产品推荐

