3维numpy数组到多索引pandas数据帧

时间:2017-04-15 14:23:56

标签: python-2.7 pandas numpy multi-index

我有一个3维= '1' GROUP BY数组,//check if username is available mDatabase.goOnline(); mDatabase.child("usernameToEmail").child(mUsernameView.getText().toString()) .addListenerForSingleValueEvent(new ValueEventListener(){ @Override public void onDataChange(DataSnapshot snapshot) { if (snapshot.exists()) { showProgress(false); mUsernameView.setError(getString(R.string.error_username_taken)); mUsernameView.requestFocus(); showKeyboard(); return; } else { register(email,username,password); } } @Override public void onCancelled(DatabaseError databaseError) { //do nothing showProgress(false); Toast.makeText(RegistrationActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show(); return; } }); 是时间维度,numpy(z, x, y)是坐标。

我想将其转换为多索引z。我希望行索引是z维度 并且每列都有一个唯一的x,y坐标值(因此,每列都会被多索引)。

最简单的情况(不是多索引):

x

我一直在尝试使用pd.MultiIndex.from_arrays将整个数组传递到多索引数据框,但是我收到一个错误: NotImplementedError:>目前不支持1 ndim Categorical

看起来应该相当简单,但我无法弄明白。

2 个答案:

答案 0 :(得分:3)

我发现Series with a Multiindex是numpy数组中最具类似性的pandas数据类型,具有任意多个维度(可能是3个或更多)。

以下是一些示例代码:

import pandas as pd
import numpy as np

time_vals = np.linspace(1, 50, 50)
x_vals = np.linspace(-5, 6, 12)
y_vals = np.linspace(-4, 5, 10)

measurements = np.random.rand(50,12,10)

#setup multiindex
mi = pd.MultiIndex.from_product([time_vals, x_vals, y_vals], names=['time', 'x', 'y'])

#connect multiindex to data and save as multiindexed Series
sr_multi = pd.Series(index=mi, data=measurements.flatten())

#pull out a dataframe of x, y at time=22
sr_multi.xs(22, level='time').unstack(level=0)

#pull out a dataframe of y, time at x=3
sr_multi.xs(3, level='x').unstack(level=1)

答案 1 :(得分:2)

我认为您可以使用panel - 然后Multiindex DataFrame添加to_frame

np.random.seed(10)
arr = np.random.randint(10, size=(5,3,2))
print (arr)
[[[9 4]
  [0 1]
  [9 0]]

 [[1 8]
  [9 0]
  [8 6]]

 [[4 3]
  [0 4]
  [6 8]]

 [[1 8]
  [4 1]
  [3 6]]

 [[5 3]
  [9 6]
  [9 1]]]

df = pd.Panel(arr).to_frame()
print (df)
             0  1  2  3  4
major minor               
0     0      9  1  4  1  5
      1      4  8  3  8  3
1     0      0  9  0  4  9
      1      1  0  4  1  6
2     0      9  8  6  3  9
      1      0  6  8  6  1

transpose也很有用:

df = pd.Panel(arr).transpose(1,2,0).to_frame()
print (df)
             0  1  2
major minor         
0     0      9  0  9
      1      1  9  8
      2      4  0  6
      3      1  4  3
      4      5  9  9
1     0      4  1  0
      1      8  0  6
      2      3  4  8
      3      8  1  6
      4      3  6  1

concat的另一种可能解决方案:

arr = arr.transpose(1,2,0)
df = pd.concat([pd.DataFrame(x) for x in arr], keys=np.arange(arr.shape[2]))
print (df)
    0  1  2  3  4
0 0  9  1  4  1  5
  1  4  8  3  8  3
1 0  0  9  0  4  9
  1  1  0  4  1  6
2 0  9  8  6  3  9
  1  0  6  8  6  1
np.random.seed(10)
arr = np.random.randint(10, size=(500,120,100))
df = pd.Panel(arr).transpose(2,0,1).to_frame()
print (df.shape)
(60000, 100)

print (df.index.max())
(499, 119)