arrays - Python Pandas : selecting 1st element in array in all cells

标签 arrays python-3.x pandas dataframe

我想要做的是选择每个单元格的第一个元素,无论列数或行数如何(它们可能会根据用户定义的标准进行更改),并从数据中创建一个新的 pandas 数据框。我的实际数据结构与下面列出的类似。

       0       1       2
0   [1, 2]  [2, 3]  [3, 6]
1   [4, 2]  [1, 4]  [4, 6]
2   [1, 2]  [2, 3]  [3, 6]
3   [4, 2]  [1, 4]  [4, 6]

我希望新的数据框看起来像:

    0   1   2
0   1   2   3
1   4   1   4
2   1   2   3
3   4   1   4

下面的代码生成一个与我的类似的数据集,并尝试在我的代码中做我想做的事情,但没有成功(d),并模仿我在类似问题中看到的成功(c;但是,只有一个柱子)。类似但不同问题的链接在这里:Python Pandas: selecting element in array column

import pandas as pd

zz = pd.DataFrame([[[1,2],[2,3],[3,6]],[[4,2],[1,4],[4,6]],
               [[1,2],[2,3],[3,6]],[[4,2],[1,4],[4,6]]])
print(zz)

x= zz.dtypes
print(x)

a = pd.DataFrame((zz.columns.values))
b = pd.DataFrame.transpose(a) 
c =zz[0].str[0] # this will give the 1st value for each cell in columns 0
d= zz[[b[0]].values].str[0] #attempt to get 1st value for each cell in all columns

最佳答案

您可以使用apply并选择列表中的第一个值使用indexing with str :

print (zz.apply(lambda x: x.str[0]))
   0  1  2
0  1  2  3
1  4  1  4
2  1  2  3
3  4  1  4

另一个解决方案 stackunstack :

print (zz.stack().str[0].unstack())
   0  1  2
0  1  2  3
1  4  1  4
2  1  2  3
3  4  1  4

关于arrays - Python Pandas : selecting 1st element in array in all cells,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41708059/

相关文章:

c++ - 在 C/C++ 中将数组转换为矩阵?

python - 如何在 python 中读取 .float 文件?

python - 使用python根据用户输入过滤csv文件

python - Pandas 值(value)错误: invalid literal for int() with base 10: ''

javascript - Javascript 中可以在变量名中使用变量吗?

python - 根据键 reshape 数组

arrays - 拆分不起作用excel VBA

django - 如何在 Django 应用程序中访问 PostgreSQL 数据库

python - 通过用列表替换单元格值来扩展 pandas 数据框

python - 使用分组依据转换数据框并包含额外的列值