I want to manage 4D arrays with pandas.

Asked 2 years ago, Updated 2 years ago, 44 views

Just like the title.
When the L-dimensional vector x is generated using i, j, and k as parameters,
I'd like to arrange the X vector components in the column and display the index as a combination of i, j, and k.
I want to manage the following generation process data well.

for range(I)
 for j range (J)
  for k range (K)
    for range (L)
     x[i,j,k,l]=fanc(i,j,k)

python pandas

2022-09-30 10:31

2 Answers

Is this what you want to do?

import pandas as pd
I,J,K,L = 3,3,3,5

# Index is a combination of range(I), range(J), and range(K)
idx=pd.MultiIndex.from_product([range(I), range(J), range(K)])
# Column is range(L)
col=range(L)
# Generating DataFrame
df=pd.DataFrame (index=idx, columns=col)

# some kind of formula
def func(i,j,k,l):
    return i+j+k+l#← First of all, define appropriately

# Fill in each cell by applying the above formula for each line
df = df.apply(lambdarrow: [func(*row.name,x)for x in row.index],axis=1)

print(df)
#       0  1  2  3   4
#0 0 0  0  1  2  3   4
#    1  1  2  3  4   5
#    2  2  3  4  5   6
#  1 0  1  2  3  4   5
#    1  2  3  4  5   6
#    2  3  4  5  6   7
#  2 0  2  3  4  5   6
#    1  3  4  5  6   7
#    2  4  5  6  7   8
#1 0 0  1  2  3  4   5
#    1  2  3  4  5   6
#    2  3  4  5  6   7
#  1 0  2  3  4  5   6
#    1  3  4  5  6   7
#    2  4  5  6  7   8
#  2 0  3  4  5  6   7
#    1  4  5  6  7   8
#    2  5  6  7  8   9
#2 0 0  2  3  4  5   6
#    1  3  4  5  6   7
#    2  4  5  6  7   8
#  1 0  3  4  5  6   7
#    1  4  5  6  7   8
#    2  5  6  7  8   9
#  2 0  4  5  6  7   8
#    1  5  6  7  8   9
#    2  6  7  8  9  10


2022-09-30 10:31

Reshape and MultiIndex seem to solve this problem.
Please let me know if there is a good way to express it


2022-09-30 10:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.