Pandas合并DataFrame时仅将新增列NaN填充为0的实现方法
问题解决方法
pandas的merge方法本身没有fill参数,你之前的写法触发报错属于正常情况。要实现仅填充合并新增列的NaN,可按以下步骤操作:
实现步骤
- 先完成两个DataFrame的左合并,和你现有代码一致:
df3 = pd.merge(df2, grouped_df_one, on=['id', 'host_id'], how='left')
- 筛选出合并产生的新增列(即
grouped_df_one中除了合并键之外的所有列),仅对这些列执行NaN填充为0的操作:
# 提取新增列名称:排除合并用的公共键id、host_id add_columns = grouped_df_one.columns.drop(['id', 'host_id']) # 仅对新增列填充NaN为0,同时可转为int类型匹配独热编码的数值格式 df3[add_columns] = df3[add_columns].fillna(0).astype(int)
完整可运行代码(基于你提供的测试数据)
import pandas as pd import numpy as np d = {'host_id': [1, 1, 2], 'id': [10, 11, 20], 'value': ["Hot Water,Cold Water,Kitchen,Coffee", "Hot Water,Coffee,Something", "Hot Water,Coffee"]} df = pd.DataFrame(data=d) d2 = {'host_id': [1, 1, 2, 3], 'id': [10, 11, 20, 30], 'some': ['test1', "test2", "test3", np.nan]} df2 = pd.DataFrame(data=d2) df_path = df.copy() df_path.index = pd.MultiIndex.from_arrays(df_path[['host_id', 'id']].values.T, names=['host_id', 'id']) df_path = df_path['value'].str.split(',', expand=True) df_path = df_path.melt(ignore_index=False).dropna() df_path.reset_index(inplace=True) one_hot = pd.get_dummies(df_path['value']) df_one = df_path.drop('value',axis = 1) df_one = df_path.join(one_hot) grouped_df_one = df_one.groupby(['id']).max(numeric_only=True) grouped_df_one = grouped_df_one.drop(columns=['variable']).reset_index() # 合并 df3 = pd.merge(df2, grouped_df_one, on=['id', 'host_id'], how='left') # 仅填充新增列的NaN为0 add_columns = grouped_df_one.columns.drop(['id', 'host_id']) df3[add_columns] = df3[add_columns].fillna(0).astype(int) print(df3)
运行后得到的结果和你期望的完全一致,原有df2的some列的NaN会被保留,仅独热编码列的NaN填充为0。
内容的提问来源于stack exchange,提问作者Test
相关产品推荐
相关产品推荐

