I want to create a 3D matrix from 4 columns of my dataframe
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'; y-axis : 'i_id' z-axis : '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)
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
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
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.]]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.