Python 将浮点列表转换为一组值
问题1:我们可以将浮点值列表转换为集合吗 数据:Python 将浮点列表转换为一组值,python,pandas,Python,Pandas,问题1:我们可以将浮点值列表转换为集合吗 数据: A B 1 [1212.0, 2121.0, 323.0] 2 [2222.0, 2222.0, 323.0] 3 [3232.0, 2323.0, 323.0] dtype(B) = object 预期产出: A B 1 {121, 2121, 323} 2 {2222, 2222, 323} 3 {3232, 2323,323} 问题2: 我有一个数据框,在这里我用歌曲合并集群,如果有一个空值,它应该忽略
A B
1 [1212.0, 2121.0, 323.0]
2 [2222.0, 2222.0, 323.0]
3 [3232.0, 2323.0, 323.0]
dtype(B) = object
预期产出:
A B
1 {121, 2121, 323}
2 {2222, 2222, 323}
3 {3232, 2323,323}
问题2:
我有一个数据框,在这里我用歌曲合并集群,如果有一个空值,它应该忽略它,只考虑有数字的值。< /P> 数据:
cluster songs
1 11
2 22
1 22
2
3 22
1
3 11
4
输出:
cluster songs
1 [11, 22, ]
2 [22, ]
3 [22,11]
4 []
预期产出:
cluster songs
1 [11, 22]
2 [22]
3 [22,11]
4 []
使用
列表理解
:
df.B = df.B.apply(lambda x: [int(i) for i in x])
或:
对于集合:
df.B = df.B.apply(lambda x: set([int(i) for i in x]))
但如果只需要转换为
set
s:
df.B = df.B.apply(set)
print (df)
A B
0 1 {2121.0, 323.0, 1212.0}
1 2 {323.0, 2222.0}
2 3 {3232.0, 323.0, 2323.0}
关于另一个问题,请使用:
uniq = df['cluster'].unique()
df = df.dropna(subset=['songs'])
df.songs = df.songs.astype(int)
df = df.groupby('cluster')['songs'].apply(list).reindex(uniq, fill_value=[])
print (df)
cluster
1 [11, 22]
2 [22]
3 [22, 11]
4 []
Name: songs, dtype: object
嘿,还有一个问题2;p@jez...AttributeError:“function”对象没有属性“apply”其B对象数据类型:object但您的错误
“function”对象没有属性“apply”
意味着您有一些命名问题,例如,某些函数被称为df
或类似的东西。尝试使用df
,df1
。。。对于数据帧。我认为问题应该在你们的真实代码中。现在我要去吃饭了,但也许你可以把你的真实代码从我的个人资料发送到我的电子邮件中,我可以查看一下。
df.B = df.B.apply(set)
print (df)
A B
0 1 {2121.0, 323.0, 1212.0}
1 2 {323.0, 2222.0}
2 3 {3232.0, 323.0, 2323.0}
uniq = df['cluster'].unique()
df = df.dropna(subset=['songs'])
df.songs = df.songs.astype(int)
df = df.groupby('cluster')['songs'].apply(list).reindex(uniq, fill_value=[])
print (df)
cluster
1 [11, 22]
2 [22]
3 [22, 11]
4 []
Name: songs, dtype: object