将字符串的数据帧列转换为列表

时间:2017-09-07 09:44:19

标签: python pandas dataframe scikit-learn

我有一些包含多个列的csv文件。

其中一列是“{0,4,5}”

形式的字符串

这些是空间中某点的坐标。

我想接受那一栏,并对所有这些点进行kmeans。

我相信(纠正我,如果我错了)我想要达到的是np.array of shape(500,3)(点的数量,定义点的特征),这就是我要做的转到kmeans。

但我失败了;

df = pd.read_csv(filename, header=None, names=['a', 'b', 'c'], delimiter=',',
                                 converters={'b': lambda x : np.array(list(map(float, x[1:-1].split(',')))) })

df.drop('a', axis=1, inplace=True)
df.drop('c', axis=1, inplace=True)

X = df['b'].values


km = KMeans(init='k-means++', n_clusters=5, n_init=10)
km.fit(X) # here it fails with "ValueError: setting an array element with a sequence."


X.shape gives (500,)   # I would expect it to be 500, 3
X[0].shape gives (3,)

print(np.unique(list(map(len, X)))) gives [3] so all the entries have three points

1 个答案:

答案 0 :(得分:0)

使用df.apply,将这些字符串值转换为列表,然后检索列表列表。

import json
X = df['b'].str.replace({'{' : '[', '}' : ']'}).apply(json.loads).values.tolist()

可选择转换为numpy数组并观察:

print(np.array(X).shape)
(500, 3)

虽然没有必要进行转换,KMeans可以很好地处理列表。

相关问题