use*_*055 4 python numpy multidimensional-array pandas
使用某些用户/项目/评级数据执行某些分类.我的问题是如何将这3列转换为用户(行),项目(列)和填充矩阵的评级数据的矩阵.
User Item ItemRating
1 23 3
2 204 4
1 492 2
3 23 4
Run Code Online (Sandbox Code Playgroud)
等等.我尝试使用DataFrame但是收到了NULL错误.
alk*_*lko 15
这是一个支点,如果我的想法是正确的,大熊猫将如下.
加载数据:
import pandas as pd
df = pd.read_csv(fname, sep='\s+', header=None)
df.columns = ['User','Item','ItemRating']
Run Code Online (Sandbox Code Playgroud)
透视它:
>>> df
User Item ItemRating
0 1 23 3
1 2 204 4
2 1 492 2
3 3 23 4
>>> df.pivot(index='User', columns='Item', values='ItemRating')
Item 23 204 492
User
1 3 NaN 2
2 NaN 4 NaN
3 4 NaN NaN
Run Code Online (Sandbox Code Playgroud)
对于一个numpy示例,让我们模拟文件StringIO:
from StringIO import StringIO
data ="""1 23 3
2 204 4
1 492 2
3 23 4"""
Run Code Online (Sandbox Code Playgroud)
并加载它:
>>> arr = np.genfromtxt(StringIO(data), dtype=int)
>>> arr
array([[ 1, 23, 3],
[ 2, 204, 4],
[ 1, 492, 2],
[ 3, 23, 4]])
Run Code Online (Sandbox Code Playgroud)
pivot基于这个答案
rows, row_pos = np.unique(arr[:, 0], return_inverse=True)
cols, col_pos = np.unique(arr[:, 1], return_inverse=True)
rows, row_pos = np.unique(arr[:, 0], return_inverse=True)
cols, col_pos = np.unique(arr[:, 1], return_inverse=True)
pivot_table = np.zeros((len(rows), len(cols)), dtype=arr.dtype)
pivot_table[row_pos, col_pos] = arr[:, 2]
Run Code Online (Sandbox Code Playgroud)
结果:
>>> pivot_table
array([[ 3, 0, 2],
[ 0, 4, 0],
[ 4, 0, 0]])
Run Code Online (Sandbox Code Playgroud)
请注意,结果不同,因为在第二种方法中,不存在的值设置为零.
选择一个更适合你的;)