我想要做的是选择每个单元格的第一个元素,无论列数或行数如何(它们可能会根据用户定义的标准进行更改),并从数据中创建一个新的 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
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/