Python 数据帧创建奇怪的数据结构
我的代码是:Python 数据帧创建奇怪的数据结构,python,pandas,dataframe,Python,Pandas,Dataframe,我的代码是: for i, out in zip(foo, output): # doing stuff and conditions # output = each value in col1 listA.append([i, out]) listA = pd.DataFrame(listA) 如您所见,每个列表都有自己的长度。我想填充每个数组以达到len=118位置。使用DataFrame()args有什么方法可以做到这一点吗?此外,它被堆叠为1列:我希望每个值都有
for i, out in zip(foo, output):
# doing stuff and conditions
# output = each value in col1
listA.append([i, out])
listA = pd.DataFrame(listA)
如您所见,每个列表都有自己的长度。我想填充每个数组以达到len=118
位置。使用DataFrame()
args有什么方法可以做到这一点吗?此外,它被堆叠为1列:我希望每个值都有自己的列(即总共118列+1个输出(col1
)输入:
data=[
[[15921, 10, 82, 22, 202973, 368, 1055, 3135]],[[15921, 10, 82, 22, 202973, 368, 1055, 3135]]
]
df=pd.DataFrame(data=data)
print(df)
0
0 [15921, 10, 82, 22, 202973, 368, 1055, 3135]
1 [15921, 10, 82, 22, 202973, 368, 1055, 3135]
从一列到多列的输出:
df_new=pd.DataFrame()
for index,row in df.iterrows():
a=np.concatenate(row)
df_new=df_new.append(pd.DataFrame(data=[a]))
print(df_new)
0 1 2 3 4 5 6 7
0 15921 10 82 22 202973 368 1055 3135
0 15921 10 82 22 202973 368 1055 3135
编辑:
缩短时间:
df=df.apply(lambda x : x.explode(),axis=1 )
你想用随机数填充这个数组吗?@sygneto,如果可能的话,用
-1
或NaN
填充,但是我检查了你的答案,它通过在循环df_new.fillna(-1)
之后添加来工作。谢谢这是可行的,但我的数据集有1.600.000行,所以访问所有行有点慢。有没有更快的解决方案?它确实有效,比以前的解决方案更快。非常感谢。
df=df.apply(lambda x : x.explode(),axis=1 )