如何将pandas中源DataFrame的EXPIRATION列完整复制到行数更少的目标DataFrame
我明白你的问题了——当destination的行数比recent少的时候,直接执行destination['EXPIRATION']= recent['EXPIRATION']只会匹配两者的索引,把recent中前N行的EXPIRATION值填充到destination里,而recent中超出destination行数的那些行就丢失了。你需要让destination完整保留recent的所有EXPIRATION值,哪怕其他列都是NaN,这里有几种可行的解决方案:
方法1:重新索引对齐(推荐,保留原destination列结构和已有数据)
这个方法会将destination的索引扩展到和recent一致,原有行的其他列数据保持不变,新增行的其他列自动填充NaN,然后再赋值EXPIRATION列:
import pandas as pd recent = pd.read_excel(r'Y:\Attachments' + '\\' + '962021.xlsx') print('HERE\n',recent) print('HERE2\n', recent['EXPIRATION']) destination= pd.read_excel(r'Y:\Attachments' + '\\' + 'Book1.xlsx') print('HERE3\n', destination) # 关键步骤:将destination的索引调整为和recent一致 destination = destination.reindex(recent.index) # 此时赋值会覆盖所有匹配索引的EXPIRATION值,新增索引行自动填充对应值 destination['EXPIRATION']= recent['EXPIRATION'] print('HERE4\n', destination)
执行后,destination会拥有和recent相同的行数,前3行(原destination的行数)的其他列保持你读取时的NaN,EXPIRATION替换为recent的前3个值;后2行的所有列(除EXPIRATION外)都是NaN,EXPIRATION则是recent的第4、5个值,完全符合你的需求。
方法2:直接创建新的DataFrame(替换原destination,仅保留列结构)
如果你不需要保留destination原有的任何数据,只想用它的列结构,然后填充recent的EXPIRATION值,可以直接创建一个新的DataFrame:
# 用recent的EXPIRATION列创建新DataFrame,指定列名为原destination的列名 destination = pd.DataFrame({'EXPIRATION': recent['EXPIRATION']}, columns=destination.columns)
这样生成的destination会和recent行数一致,只有EXPIRATION列有值,其他所有列都是NaN。
方法3:合并追加行(保留原destination数据,追加新行)
如果你想保留destination原有的行数据,然后把recent中超出的行追加进去,可以用concat:
# 先把recent的EXPIRATION列转换成和destination同列结构的DataFrame recent_exp_df = pd.DataFrame({'EXPIRATION': recent['EXPIRATION']}, columns=destination.columns) # 合并原destination和recent中超出的部分,重置索引 destination = pd.concat([destination, recent_exp_df.iloc[len(destination):]], ignore_index=True)
这个方法会保留destination原有的3行数据,然后把recent中第4、5行的EXPIRATION值作为新行追加进去,新行的其他列都是NaN。
内容的提问来源于stack exchange,提问作者daniel

