通过使用2个数据框创建3D熊猫数据框

时间:2020-08-23 09:00:15

标签: python pandas dataframe

我尝试从具有相同形状的2个数据帧中获得3D数据帧。如果我们以下面的脚本为例,我想创建一个3D数据框,其中包含2行(a和b),3列(A,B和C)和2项(df1和df2)。同样要明确的是,我试图用数字解释我的问题。

def image2np(name_list,read = True, save=True, path="./VOC2012/JPEGImages/"):
    if read and os.path.isfile("images.npy"):
        print("reading images .... ")
        images = np.load("images.npy")

    else:
        images = []
        for name in name_list:
            img = get_image(name)
            if img is not None:
                images.append(img)
        print("total number of images read :{}".format(len(images)))
        images = np.array(images)
        if save and read == False:
            np.save("images.npy",images)

    return images

我看到了相关问题,并尝试了其中一些。我尝试使用pd.MultiIndex,但是由于“ ValueError:级别和标签的长度必须相同”而获得错误。

是否有如下图所示的方法来获取3D数据帧?

谢谢。

1

2 个答案:

答案 0 :(得分:0)

可以实施

This library来支持这一点。我不知道这个图书馆的存在。这是我第一次安装此问题并从official reference获取信息以创建响应。谢谢您的这次机会。

import pandas as pd

df1 = pd.DataFrame([[1, 2, 11], [3, 4, 12]], columns=['A', 'B', 'C'], index=['a', 'b'])
df2 = pd.DataFrame([[5, 6, 13], [7, 8, 14]], columns=['A', 'B', 'C'], index=['a', 'b'])
ds1 = df1.to_xarray()

enter image description here

ds2 = df2.to_xarray()

enter image description here

将xarray导入为xr ds_all = xr.concat([ds1,ds2],dim ='new_dim')

enter image description here

df_all = ds_all.to_dataframe()
df_all
        A   B   C
index   new_dim         
a   0   1   2   11
    1   5   6   13
b   0   3   4   12
    1   7   8   14

答案 1 :(得分:0)

简单来说,您可以这样做。

import pandas as pd

df = pd.DataFrame(columns=['col'])

df1 = pd.DataFrame([[1, 2, 11], [3, 4, 12]], columns=['A', 'B', 'C'], index=['a', 'b'])
df2 = pd.DataFrame([[5, 6, 13], [7, 8, 14]], columns=['A', 'B', 'C'], index=['a', 'b'])

df = df.append({'col': df1}, ignore_index=True)
df = df.append({'col': df2}, ignore_index=True)

print(df)

enter image description here

print(df.iloc[1])

enter image description here