我在Python Pandas中有如下数据框:

df = pd.DataFrame({
    'id' : [999, 999, 999, 185, 185, 185, 999, 999, 999],
    'target' : [1, 1, 1, 0, 0, 0, 1, 1, 1],
    'event': ['2023-01-01', '2023-01-02', '2023-02-03', '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-01', '2023-01-02', '2023-01-03'],
    'survey': ['2023-02-02', '2023-02-02', '2023-02-02', '2023-03-10', '2023-03-10', '2023-03-10', '2023-04-22', '2023-04-22', '2023-04-22'],
    'event1': [1, 6, 11, 16, np.nan, 22, 74, 109, 52],
    'event2': [2, 7, np.nan, 17, 22, np.nan, np.nan, 10, 5],
    'event3': [3, 8, 13, 18, 23, np.nan, 2, np.nan, 99],
    'event4': [4, 9, np.nan, np.nan, np.nan, 11, 8, np.nan, np.nan],
    'event5': [5, np.nan, 15, 20, 25, 1, 1, 3, np.nan]
})

df = df.fillna(0)
df

enter image description here

Requirements:

我需要在我的数据框中保留列"id"中没有重复的值,同时也保留具有来自列"Survey"的该id的没有重复的值的所有行.

例如,如您在id=999的示例中所看到的,我们在"Survey"列中有值2023-02-02或2023-04-22,所以我需要保留id=999、2023-02-02或2023-04-022的所有行.

Example of needed result:

因此,我需要如下内容:

df = pd.DataFrame({
    'id' : [999, 999, 999, 185, 185, 185],
    'target' : [1, 1, 1, 0, 0, 0],
    'event': ['2023-01-01', '2023-01-02', '2023-02-03', '2023-01-01', '2023-01-02', '2023-01-03'],
    'survey': ['2023-02-02', '2023-02-02', '2023-02-02', '2023-03-10', '2023-03-10', '2023-03-10'],
    'event1': [1, 6, 11, 16, np.nan, 22],
    'event2': [2, 7, np.nan, 17, 22, np.nan],
    'event3': [3, 8, 13, 18, 23, np.nan],
    'event4': [4, 9, np.nan, np.nan, np.nan, 11],
    'event5': [5, np.nan, 15, 20, 25, 1]
})

df = df.fillna(0)
df

enter image description here

我如何在Python Pandas中做到这一点?

推荐答案

您可以保留每个ID的第一个调查日期为groupby.transform:

out = df[df.groupby('id')['survey'].transform('first').eq(df['survey'])]

输出:

    id  target       event      survey  event1  event2  event3  event4  event5
0  999       1  2023-01-01  2023-02-02     1.0     2.0     3.0     4.0     5.0
1  999       1  2023-01-02  2023-02-02     6.0     7.0     8.0     9.0     0.0
2  999       1  2023-02-03  2023-02-02    11.0     0.0    13.0     0.0    15.0
3  185       0  2023-01-01  2023-03-10    16.0    17.0    18.0     0.0    20.0
4  185       0  2023-01-02  2023-03-10     0.0    22.0    23.0     0.0    25.0
5  185       0  2023-01-03  2023-03-10    22.0     0.0     0.0    11.0     1.0

Python相关问答推荐

合并其中一个具有重叠范围的两个框架的最佳方法是什么?

已安装' owiener ' Python模块,但在导入过程中始终没有名为owiener的模块

Altair -箱形图边界设置为黑色,中线设置为红色

Polars Dataframe:如何按组删除交替行?

如何使用bs 4从元素中提取文本

是什么导致对Python脚本的jQuery Ajax调用引发500错误?

opencv Python稳定的图标识别

如何根据条件在多指标框架上进行groupby

如何从FDaGrid实例中删除某些函数?

线性模型PanelOLS和statmodels OLS之间的区别

如何在箱形图中添加绘制线的传奇?

. str.替换pandas.series的方法未按预期工作

scikit-learn导入无法导入名称METRIC_MAPPING64'

如何在polars(pythonapi)中解构嵌套 struct ?

基于索引值的Pandas DataFrame条件填充

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

通过ManyToMany字段与Through在Django Admin中过滤

在Python中调用变量(特别是Tkinter)

具有相同图例 colored颜色 和标签的堆叠子图

为什么在FastAPI中创建与数据库的连接时需要使用生成器?