我有一个数据帧,其中一列具有相同长度的numpy.ndarray值,
df[list][0]
Out[92]:
array([0. , 0. , 0. , ..., 0.29273096, 0.30691767,
0.27531403])
我想将这些列表值转换为数据帧,并作为df.iloc [,1:len(list)]的单列值填充
示例
list 1 2 3 ...
0 [..] 0 0 0
1 [..] 0.570642 0.181552 0.794599
2 [..] 0.568440 0.501638 0.186635
3 [..] 0.679125 0.642817 0.697628
.
.
答案 0 :(得分:2)
我认为需要将值转换为list
,然后调用DataFrame
建设者:
df = pd.DataFrame({'list':[np.array([1,2,3]), np.array([7,8,3]), np.array([3,7,0])]})
print (df)
list
0 [1, 2, 3]
1 [7, 8, 3]
2 [3, 7, 0]
df = pd.DataFrame(df['list'].values.tolist(), index=df.index)
print (df)
0 1 2
0 1 2 3
1 7 8 3
2 3 7 0
最后join
个到原始df
:
df = df.join(pd.DataFrame(df['list'].values.tolist(), index=df.index))
print (df)
list 0 1 2
0 [1, 2, 3] 1 2 3
1 [7, 8, 3] 7 8 3
2 [3, 7, 0] 3 7 0
另一个较慢的解决方案是:
df = df.join(df['list'].apply(pd.Series))
性能:
该图是使用perfplot创建的:
np.random.seed(57)
def apply(df):
df = df.join(df['list'].apply(pd.Series))
return df
def values(df):
df = df.join(pd.DataFrame(df['list'].values.tolist(), index=df.index))
return df
def make_df(n):
df = pd.DataFrame({'list': np.random.randint(10, size=(n, 10)).tolist()})
return df
perfplot.show(
setup=make_df,
kernels=[ apply, values],
n_range=[2**k for k in range(2, 17)],
logx=True,
logy=True,
equality_check=False, # rows may appear in different order
xlabel='len(df)')