Pandas 按 Id 分组并获取非 NaN 值

Pandas Grouping by Id and getting non-NaN values

我有一个 table 可以跟踪对 salesforce 记录的每个字段所做的更改。我的目标是按 saleforce_id 列分组,并将所有行合并为一行,如果有任何文本值,则用文本值替换空值。我尝试了 groupby 的不同变体,但似乎无法获得所需的输出。

使用meltpivot:

out = df.melt('id').dropna() \
        .pivot('id', 'variable', 'value') \
        .rename_axis(index=None, columns=None)
print(out)

# Output:
    A   B   C
1  A1  B1  C2

设置:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': [1, 1, 1],
                   'A': ['A1', np.nan, np.nan],
                   'B': [np.nan, 'B1', np.nan],
                   'C': [np.nan, np.nan, 'C2'],
                   'D': [np.nan, np.nan, np.nan]})
print(df)

# Output:
   id    A    B    C   D
0   1   A1  NaN  NaN NaN
1   1  NaN   B1  NaN NaN
2   1  NaN  NaN   C2 NaN

这应该做你想做的事:

df.groupby('salesforce_id').first().reset_index(drop=True)

这会将所有列合并为一列,只保留每个 运行 的非 NaN 值(除非该行的所有列中都没有非 NaN 值;然后是最终合并的列将为 NaN)。