python - Pandas 数据框包含列表

标签 python pandas matrix data-cleaning

假设我有这样一个数据框:

lst1 = [[1,3,4,5],[1,2,3,3],[2,3,4,5],[3,4,5,5]]
lst2 = [[1,2,3,1],[1,4,1,2],[3,3,1,5],[2,4,1,5]]
lst3 = [[1,2,3,3],[3,2,1,2],[1,3,1,4],[2,4,3,5]]
percentile_list = pd.DataFrame({'lst1Tite' : lst1,
 'lst2Tite' : lst2,
 'lst3Tite':lst3
})

> precentile_list    
        lst1Tite    lst2Tite    lst3Tite
0   [1, 3, 4, 5]    [1, 2, 3, 1]    [1, 2, 3, 3]
1   [1, 2, 3, 3]    [1, 4, 1, 2]    [3, 2, 1, 2]
2   [2, 3, 4, 5]    [3, 3, 1, 5]    [1, 3, 1, 4]
3   [3, 4, 5, 5]    [2, 4, 1, 5]    [2, 4, 3, 5]

现在我想提取第 0 行,并将第 0 行转换为这样的数据框:

> percentile_0
col1    col2    col3    col4
0   1   3   4   5
1   1   2   3   1
2   1   2   3   3

我该怎么做?

如果我想将 precentile_list 转换为像 percentile_0 这样的数据框怎么办?

最佳答案

您可以使用 apply 并在行上应用 Series 构造函数:

In [17]:
percentile_list.iloc[0].apply(pd.Series)

Out[17]:
          0  1  2  3
lst1Tite  1  3  4  5
lst2Tite  1  2  3  1
lst3Tite  1  2  3  3

如果您特别喜欢所需的输出:

In [20]:
pd.DataFrame(percentile_list.iloc[0].apply(pd.Series).values, columns = ['col1','col2','col3','col4'])

Out[20]:
   col1  col2  col3  col4
0     1     3     4     5
1     1     2     3     1
2     1     2     3     3

您可以将每个 df 存储在一个字典中,并使用您想要的名称命名的键:

In [41]:
d={}
for l in percentile_list.index:
    d['percentile_' + str(l)] = pd.DataFrame(percentile_list.loc[l].apply(pd.Series).values, columns = ['col1','col2','col3','col4'])
d

Out[41]:
{'percentile_0':    col1  col2  col3  col4
 0     1     3     4     5
 1     1     2     3     1
 2     1     2     3     3, 'percentile_1':    col1  col2  col3  col4
 0     1     2     3     3
 1     1     4     1     2
 2     3     2     1     2, 'percentile_2':    col1  col2  col3  col4
 0     2     3     4     5
 1     3     3     1     5
 2     1     3     1     4, 'percentile_3':    col1  col2  col3  col4
 0     3     4     5     5
 1     2     4     1     5
 2     2     4     3     5}

这是第一个键:

In [42]:
d['percentile_0']

Out[42]:
   col1  col2  col3  col4
0     1     3     4     5
1     1     2     3     1
2     1     2     3     3

关于python - Pandas 数据框包含列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37464656/

相关文章:

python - 使用 cx_Freeze 卡住 pandas/NumPy 1.7.0 代码时出错

python - 从 numpy 矩阵获取项目,索引位于数组中

matlab - 如果矩阵的第一列提供索引值,则求子矩阵的均值

python - 如何在 sympy 中对向量求导?

python - 如何将 pandas 数据框中的时间戳转换为 datetime.date?

c++ - 漂亮的 map 打印机抛出类型错误

python - 带 for 循环的非常小的数字 python

python - 将一种方法应用于 Pandas 数据框中的几个选定列

python - 将一个数据帧减去另一个数据帧系列

专门化模板化父类(super class)的类的 C++ 工厂