Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有 A 列和 B 列,其中 A 列很少有数据,而 B 列完全满了。我想将 B 列复制到 A 列,并始终保留 A 列相对于 B 列的任何值。
我的数据框的长度约为 150 万,因此 df.iterrows() 是一个解决方案,但它会非常耗时。是否有任何优化的熊猫功能或技巧可以尽可能有效地做到这一点?
我会使用 .loc 来完成这项工作
df.loc[df['A'].isnull(), 'A'] = df['B']
如下所示:位于“A”列为空的位置,并将“A”列设置为“B”列。
你可以尝试类似的东西
df["A"][df["A"].isna()] = df["B"][df["A"].isna()]
编辑:评论者指出,pandas 中已经有一种方法可以解决这个问题,所以请改用它。