gpt4 book ai didi

python - 合并 pandas DataFrame 中的两列

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:12 26 4
gpt4 key购买 nike

给定以下 DataFrame:

      A     B
0 -10.0 NaN
1 NaN 20.0
2 -30.0 NaN

我想合并 AB 列,用值填充 A 列中的 NaN 单元格从 B 列开始,然后删除 B 列,生成如下所示的 DataFrame:

     A
0 -10.0
1 20.0
2 -30.0

我已经设法通过使用 iterrows() 函数解决了这个问题。

完整代码示例:

import numpy as np
import pandas as pd

example_data = [[-10, np.NaN], [np.NaN, 20], [-30, np.NaN]]

example_df = pd.DataFrame(example_data, columns = ['A', 'B'])

for index, row in example_df.iterrows():
if pd.isnull(row['A']):
row['A'] = row['B']

example_df = example_df.drop(columns = ['B'])

example_df

这似乎工作正常,但我在 the documentation for iterrows() 中找到了此信息:

You should never modify something you are iterating over.

看来我做错了。

要达到相同的结果,更好/推荐的方法是什么?

最佳答案

使用Series.fillnaSeries.to_frame :

df = df['A'].fillna(df['B']).to_frame()
#alternative
#df = df['A'].combine_first(df['B']).to_frame()
print (df)
A
0 -10.0
1 20.0
2 -30.0

如果有更多的列并且每行需要第一个非缺失值,请使用通过一个元素列表为一列选择第一列来回填缺失值DataFrame:

df = df.bfill(axis=1).iloc[:, [0]]
print (df)
A
0 -10.0
1 20.0
2 -30.0

关于python - 合并 pandas DataFrame 中的两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56038964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com