在for循环中创建新的df库仑

问题描述 投票:0回答:2

我有一个带有'x'列的df,我想从中采样数据并将其存储在新的数据帧df_pull中。我想在for循环中重复此过程,例如10次​​。我的问题是:“未定义名称'df_pull'”。当然,这是因为我没有反抗df_pull,但是我如何创建一个空的df。这不可能吗?通过创建很多if列表,我感到非常满意,但是我确信这不是最好的解决方案。

for i in np.arange(10):
    df_pull[[i]] = df['x'].sample(frac=1)

谢谢。

python pandas sample
2个回答
2
投票

将列表理解与concat一起使用,并且对于DataFrame.reset_indexDataFrame.reset_index一样重要,以避免相同的列值(因为索引alignmenet):

drop=True

您的解决方案使用空的DataFrame以及r = np.arange(10) L = [df['x'].sample(frac=1).reset_index(drop=True) for i in r] df_pull = pd.concat(L, axis=1, keys=r)

DataFrame.reset_index

1
投票

您可以创建一个空的DateFrame只是

df = pd.DataFrame({
         'y':[7,8,9,4,2,3],
         'x':[1,3,5,7,1,0],

})

df_pull = pd.DataFrame()
for i in np.arange(10):
    df_pull[i] = df['x'].sample(frac=1).reset_index(drop=True)

print (df_pull)
   0  1  2  3  4  5  6  7  8  9
0  1  7  1  1  1  5  3  5  3  1
1  7  1  5  5  0  1  1  1  7  7
2  5  0  0  7  1  3  5  3  1  5
3  3  3  3  0  3  0  7  1  1  3
4  0  1  7  1  5  7  1  7  5  1
5  1  5  1  3  7  1  0  0  0  0

如果要与第一个df相同的列

pull_df = pd.DataFrame()
© www.soinside.com 2019 - 2024. All rights reserved.