嵌套列表到python数据帧

问题描述 投票:0回答:1

我有一个以下格式的嵌套numpy.ndarray(每个子列表具有相同的大小)

len(exp_data) # Timepoints
Out[205]: 42

len(exp_data[0])
Out[206]: 1

len(exp_data[0][0]) # Y_bins
Out[207]: 13

len(exp_data[0][0][0]) # X_bins
Out[208]: 43

type(exp_data[0][0][0][0])
Out[209]: numpy.float64

我想将它们移动到一个pandas DataFrame中,这样就有3列从0到N编号,最后一列用浮点值。我可以通过一系列循环来做到这一点,但这似乎是解决问题的一种非常有效的方法。

另外我想摆脱任何nan值(样本数据中没有)。我是否在创建df之后执行此操作,或者是否有办法在第一时间跳过添加它们?

注意:以下代码已经过编辑,我添加了样本数据

import random
import numpy as np
import pandas as pd

exp_data = [[[ [random.random() for x in range (5)],
                  [random.random() for x in range (5)],
                  [random.random() for x in range (5)],
                   ]]]*5
exp_data[0][0][0][1]=np.nan

df = pd.DataFrame(columns = ['Timepoint','Y_bin','X_bin','Values'])

for t,timepoint in enumerate(exp_data):
    for y,y_bin in enumerate(timepoint[0]):
        for x,x_bin in enumerate(y_bin):
            df.loc[len(df)] = [int(t),int(y),int(x),x_bin]

df = df.dropna().reset_index(drop=True)

最终格式应该如下(除了我最好喜欢整数而不是前三列中的浮点数,但不是必需的; int(t)等不能做到这一点)

df
Out[291]: 
    Timepoint  Y_bin  X_bin    Values
0         0.0    0.0    0.0  0.095391
1         0.0    0.0    2.0  0.963608
2         0.0    0.0    3.0  0.855735
3         0.0    0.0    4.0  0.392637
4         0.0    1.0    0.0  0.555199
5         0.0    1.0    1.0  0.118981
6         0.0    1.0    2.0  0.201782
...

len(df) # has received a total of 75 (5*3*5) input values of which 5 are nan
Out[293]: 70
python pandas nested-lists
1个回答
0
投票

通过添加这段代码来更改浮动输出的格式

pd.options.display.float_format = '{:,.0f}'.format

在这样的代码结束时更改格式

df = pd.DataFrame(columns = columns)
for t,timepoint in enumerate(exp_data):
for y,y_bin in enumerate(timepoint[0]):
    for x,x_bin in enumerate(y_bin):
        df.loc[len(df)] = [t,y,x,x_bin]
df.dropna().reset_index(drop=True)

pd.options.display.float_format = '{:,.0f}'.format
df
Out[250]: 
    Timepoint  Y_bin  X_bin    Values
0          0    4      10      -2
1          0    4      11      -1
2          0    4      12      -2
3          0    4      13      -2
4          0    4      14      -2
5          0    4      15      -2
6          0    4      16      -3

...

© www.soinside.com 2019 - 2024. All rights reserved.