迭代包含嵌套数组的 Pandas 数据框列

Car*_*lho 3 python dataframe pandas

我希望你能帮助我解决这个问题

我在下面有这些数据(列名称随便)

data=([['file0090',
    ([[ 84,  55, 189],
   [248, 100,  18],
   [ 68, 115,  88]])],
   ['file6565',
    ([[ 86,  58, 189],
   [24, 10,  118],
   [ 68, 11,  8]])
   ]])
Run Code Online (Sandbox Code Playgroud)

我需要将第 0 列和第 1 列迭代到排序列表中,我可以使用此输出转换为数据框:

col0          col1  col2   col3 
file0090      84     55     189
file0090      248    100      1
file0090      68     115    88
file6565      86     58    189
file6565      24    10     118
file6565      68    11      8
Run Code Online (Sandbox Code Playgroud)

我已经用 iterrows、iteritems、items 和附加到列表中测试了所有数据帧迭代,但结果总是围绕相同的输出,我不知道这些项目是如何从这些数组中分离出来的

如果您能提供帮助,请提前致谢。

Dha*_*unk 6

你可以试试这个:-

data_f = [[i[0]]+j for i in data for j in i[1]]
df = pd.DataFrame(data_f, columns =['col0','col1','col2','col3'])
Run Code Online (Sandbox Code Playgroud)

输出:-

col0          col1  col2   col3 
file0090      84     55     189
file0090      248    100      1
file0090      68     115    88
file6565      86     58    189
file6565      24    10     118
file6565      68    11      8
Run Code Online (Sandbox Code Playgroud)

  • 使用 %%timeit 这个解决方案击败了@YOBEN_S 解决方案。循环并不总是坏事的一个证明。 (2认同)

ank*_*_91 5

您可以在从一系列列表中创建另一个 df 之后explode使用 a join

df = pd.DataFrame(data).add_prefix('col')

out = df.explode('col1').reset_index(drop=True)
out = out.join(pd.DataFrame(out.pop('col1').tolist()).add_prefix('col_'))
Run Code Online (Sandbox Code Playgroud)

如果列表结构相似,则添加另一个解决方案:

l = [*itertools.chain.from_iterable(data)]
pd.DataFrame(np.vstack(l[1::2]),index = np.repeat(l[::2],len(l[1])))
Run Code Online (Sandbox Code Playgroud)
      col0  col_0  col_1  col_2
0  file0090     84     55    189
1  file0090    248    100     18
2  file0090     68    115     88
3  file6565     86     58    189
4  file6565     24     10    118
5  file6565     68     11      8
Run Code Online (Sandbox Code Playgroud)