[英]create a 3D matrix from 4 columns of a Dataframe
I want to create a 3D matrix from 4 columns of my dataframe我想从我的数据框的 4 列创建一个 3D 矩阵
Input:输入:
df = pd.DataFrame({
"u_id": [55218,55218,55218,55222],
"i_id": [0,0,1,1],
"Num": [0,2,1,2]
"rating":[-1,2,0,2]})
x-axis : 'u_id'; x 轴:'u_id'; y-axis : 'i_id' z-axis : 'Num' y 轴:'i_id' z 轴:'Num'
And the value in the Matrix should be 'rating'矩阵中的值应该是“评级”
The result should be结果应该是
[[[NaN,NaN],
[-1 ,NaN]],
[[NaN,NaN],
[ 0,NaN]],
[[ 2,NaN],
[NaN,2]]]
What i tried so far:到目前为止我尝试过的:
x = df['u_id']
y = df['i_id']
z = df['Num']
value = df['rating']
Matrix = [[0 for m in len(z)] for m in len(z)] for c in len(x):
Matrix[c][r][m]= value
but this doesn't work.但这不起作用。
I think your expected output doesn't represent the information in your dataframe.我认为您的预期输出不代表您的数据框中的信息。 But if you want the values of rating
placed with the other columns as indices in a 3D array with shape (3,2,2)
但是,如果您希望将rating
值与其他列一起放置作为具有形状(3,2,2)
的 3D 数组中的索引
Setup the input data设置输入数据
import numpy as np
import pandas as pd
df = pd.DataFrame({
"u_id": [55218,55218,55218,55222],
"i_id": [0,0,1,1],
"Num": [0,2,1,2], # <-- here was a small typo in your code
"rating":[-1,2,0,2]})
df
Out:出去:
u_id i_id Num rating
0 55218 0 0 -1
1 55218 0 2 2
2 55218 1 1 0
3 55222 1 2 2
First convert u_id
to suitable indices首先将u_id
转换为合适的索引
df['u_id'] = df['u_id'].astype('category').cat.codes
df[['Num','u_id','i_id','rating']] # order columns to correspond to coordinates
Out:出去:
Num u_id i_id rating
0 0 0 0 -1
1 2 0 0 2
2 1 0 1 0
3 2 1 1 2
Then create the output array and fill in the rating
values然后创建输出数组并填写rating
值
x = np.full(df[['Num','u_id','i_id']].nunique(), np.nan)
x[df['Num'], df['u_id'], df['i_id']] = df['rating']
x
Out:出去:
array([[[-1., nan],
[nan, nan]],
[[nan, 0.],
[nan, nan]],
[[ 2., nan],
[nan, 2.]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.