删除包含多个元素的列表(列内),并将其转换为常规列

2024-09-28 21:11:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框如下所示:

 id 
444343                           [2]
50224018                         [7]
4284                             [2]
226818                         [2, 36]
28484                       [29, 15, 52114, 47]
229261                          [20]

此数据帧是这行代码的结果:

df= df.groupby('id').station.unique()

这给了我数据帧中每个组的唯一电台。 现在我需要删除所有具有多个站点的行,并将该行转换为常规整数。关于具体例子:

 ID                            station
444343                           2
50224018                         7
4284                             2
229261                          20

但我甚至无法访问此列,我尝试添加它的名称df.columns = ["number_from", "station"],以使用索引访问它。。没什么


Tags: columns数据代码名称iddf站点整数
3条回答

您可以使用transform检查nunique

df1=df[df.groupby('id').station.transform('nunique')==1].copy()
df = pd.DataFrame(data={"id":[1,2,3,4,5],
                       "station":[[2],[7],[2],[2,36],[29, 15, 52114, 47]]})

df['more_than_one_station'] = df['station'].apply(lambda x:True if len(x)>1 else False)

df = df[df["more_than_one_station"]==False]

df['station'] = df['station'].apply(lambda x : pd.Series(x))

df.drop(['more_than_one_station'],axis=1,inplace=True)

你可以做:

df=df[df.station.str.len().eq(1)].assign(station=df.station.str[0])

         id   station
0    444343        2
1  50224018        7
2      4284        2
5    229261       20

相关问题 更多 >