如何在Pandas中添加长度超DataFrame的列并填充原列空值
解决方法
有两种简洁的方式可以实现需求:
方法一:基于新列构造DataFrame后合并
import pandas as pd # 原DataFrame df = pd.DataFrame({'col1': [1,2,3,4]}) # 待添加的新列数据 new_col = range(9) # 创建包含新列的DataFrame,索引覆盖新列的所有行 new_df = pd.DataFrame({'new_col': new_col}) # 将原列数据合并到新DataFrame,缺失行填充为空字符串 new_df['col1'] = df['col1'].reindex(new_df.index).fillna('')
方法二:扩展原DataFrame索引后填充
import pandas as pd df = pd.DataFrame({'col1': [1,2,3,4]}) new_col = range(9) # 扩展原DataFrame的索引,匹配新列的长度 df = df.reindex(range(len(new_col))) # 添加新列 df['new_col'] = new_col # 把原列的缺失值替换为空字符串 df['col1'] = df['col1'].fillna('')
两种方法最终都会得到目标结果:
col1 new_col 0 1 0 1 2 1 2 3 2 3 4 3 4 4 5 5 6 6 7 7 8 8
内容的提问来源于stack exchange,提问作者frank
相关产品推荐
相关产品推荐

