我想使用'cluster1'字典填充名为pandas series
的空Cluster
。
有关数据的一些背景信息:
data.StringTogeth1
print(type(data.StringTogeth1))
print(type(data.StringTogeth1[0]))
输出:
0 love dog cute think
1 dog look weird
2 think look like cupacak
3 want snowman thank jerk grrr make mad
4 hey know time babi shark dodododo
5 dog awesom
Name: StringTogeth1, dtype: object
<class 'pandas.core.series.Series'>
<class 'str'>
输入:
nclusters1 = 4
clusters1 = cluster_sentences(data.StringTogeth1, nclusters1)
data['Cluster'] = pd.Series()
print(clusters1)
输出:
{1: [0, 2], 2: [1, 5], 0: [3], 3: [4]}
所以clusters1
转换为
{cluster number: [index from series,index from series], etc..}
因此数据框应如下所示:
Id StringTogeth1 Cluster
0 1 love dog cute think 1
1 2 dog look weird 2
2 3 think look like cupacak 1
3 4 want snowman thank jerk grrr make mad 0
4 5 hey know time babi shark dodododo 3
5 6 dog awesom 2
答案 0 :(得分:1)
IIUC,您可以展平和反转clusters1
,然后将其分配回去:
df['Clusters'] = pd.Series({v: k for k, V in clusters1.items() for v in V})
df
Id StringTogeth1 Clusters
0 0 love dog cute think 1
1 1 dog look weird 2
2 2 think look like cupacak 1
3 3 want snowman thank jerk grrr make mad 0
4 4 hey know time babi shark dodododo 3
5 5 dog awesom 2
在哪里
{v: k for k, V in clusters1.items() for v in V}
# {0: 1, 1: 2, 2: 1, 3: 0, 4: 3, 5: 2}
...是索引到群集标签的映射。
提示:无需使用空序列初始化列。