Skip to main content
 首页 » 编程设计

python之Dataframe 到 numpy 数组中,值以逗号分隔

2025年05月04日15lexus

场景

我已经将 csv(\t 分隔)读入 Dataframe,现在需要以 numpy 数组格式进行聚类而不更改类型

问题

到目前为止,根据尝试过的引用资料(如下),我未能获得所需的输出。我要获取的两列的值在 int64/float64 中,如下所示

         uid   iid       rat 
0        196   242  3.000000 
1        186   302  3.000000 
2         22   377  1.000000 

目前我只对 iid 和 rat 感兴趣,并将其传递给 Kmeans.fit() 方法,而这也不会包含 EPSILON。我需要以下格式

预期格式

[[242, 3.000000], 
[302, 3.000000], 
[22, 1.000000]] 

尝试失败

X = values[:, 1:2] 
Y = values[:, 2:3] 
someArray = np.array([X,Y]) 
print someArray 

死刑不告别

[[[  2.42000000e+02] 
  [  3.02000000e+02] 
  [  3.77000000e+02] 
  ...,  
  [  1.35200000e+03] 
  [  1.62600000e+03] 
  [  1.65900000e+03]] 
 [[  3.00000000e+00] 
  [  3.00000000e+00] 
  [  1.00000000e+00] 
  ...,  
  [  1.00000000e+00] 
  [  1.00000000e+00] 
  [  1.00000000e+00]]] 

到目前为止无帮助的引用

  1. This one
  2. This two
  3. This three
  4. This four

编辑 1

尝试了 np_df = np.genfromtxt('AllData.csv', delimiter='\t', unpack=True) 并得到了这个

[[             nan   1.96000000e+02   1.86000000e+02 ...,   4.79000000e+02 
    4.79000000e+02   4.79000000e+02] 
 [             nan   2.42000000e+02   3.02000000e+02 ...,   1.36000000e+03 
    1.39400000e+03   1.65200000e+03] 
 [             nan   3.00000000e+00   3.00000000e+00 ...,   2.00000000e+00 
    1.92803605e+00   1.00000000e+00]] 

请您参考如下方法:

使用基于标签的选择和生成的 pandas 对象的 .values 属性,这将是某种 numpy 数组:

>>> df 
   uid  iid  rat 
0  196  242  3.0 
1  186  302  3.0 
2   22  377  1.0 
>>> df.loc[:,['iid','rat']] 
   iid  rat 
0  242  3.0 
1  302  3.0 
2  377  1.0 
>>> df.loc[:,['iid','rat']].values 
array([[ 242.,    3.], 
       [ 302.,    3.], 
       [ 377.,    1.]]) 

请注意,您的整数列将提升为 float 。

另请注意,可以通过不同的方式处理此特定选择:

>>> df.iloc[:, 1:] # integer-position based 
   iid  rat 
0  242  3.0 
1  302  3.0 
2  377  1.0 
>>> df[['iid','rat']] # plain indexing performs column-based selection 
   iid  rat 
0  242  3.0 
1  302  3.0 
2  377  1.0 

我喜欢基于标签的,因为它更明确。

编辑

您没有看到逗号的原因是 numpy 数组的打印方式造成的:

>>> df[['iid','rat']].values 
array([[ 242.,    3.], 
       [ 302.,    3.], 
       [ 377.,    1.]]) 
>>> print(df[['iid','rat']].values) 
[[ 242.    3.] 
 [ 302.    3.] 
 [ 377.    1.]] 

实际上,它是 the difference between the str and repr numpy 数组的结果:

>>> print(repr(df[['iid','rat']].values)) 
array([[ 242.,    3.], 
       [ 302.,    3.], 
       [ 377.,    1.]]) 
>>> print(str(df[['iid','rat']].values)) 
[[ 242.    3.] 
 [ 302.    3.] 
 [ 377.    1.]]