python - 按行随机连接数据帧

标签 python numpy pandas

如何按行随机合并、连接或连接 pandas 数据帧?假设我有四个这样的数据框(行数更多):

df1 = pd.DataFrame({'col1':["1_1", "1_1"], 'col2':["1_2", "1_2"], 'col3':["1_3", "1_3"]})
df2 = pd.DataFrame({'col1':["2_1", "2_1"], 'col2':["2_2", "2_2"], 'col3':["2_3", "2_3"]})
df3 = pd.DataFrame({'col1':["3_1", "3_1"], 'col2':["3_2", "3_2"], 'col3':["3_3", "3_3"]})
df4 = pd.DataFrame({'col1':["4_1", "4_1"], 'col2':["4_2", "4_2"], 'col3':["4_3", "4_3"]})

我怎样才能加入这四个数据帧随机输出这样的东西(它们是随机合并的一行一行):

  col1 col2 col3 col1 col2 col3 col1 col2 col3 col1 col2 col3
0  1_1  1_2  1_3  4_1  4_2  4_3  2_1  2_2  2_3  3_1  3_2  3_3
1  2_1  2_2  2_3  1_1  1_2  1_3  3_1  3_2  3_3  4_1  4_2  4_3

我在想我可以做这样的事情:

my_list = [df1,df2,df3,df4]
my_list = random.sample(my_list, len(my_list))
df = pd.DataFrame({'empty' : []})

for row in df:
    new_df = pd.concat(my_list, axis=1)

print new_df

上面的 for 语句不会超过第一行,之后的每一行(我有更多)都是一样的,即它只会随机播放一次:

  col1 col2 col3 col1 col2 col3 col1 col2 col3 col1 col2 col3
0  4_1  4_2  4_3  1_1  1_2  1_3  2_1  2_2  2_3  3_1  3_2  3_3
1  4_1  4_2  4_3  1_1  1_2  1_3  2_1  2_2  2_3  3_1  3_2  3_3

最佳答案

也许是这样的?

import random
import numpy as np

dfs = [df1, df2, df3, df4]
n = np.sum(len(df.columns) for df in dfs)
pd.concat(dfs, axis=1).iloc[:, random.sample(range(n), n)]

Out[130]: 
  col1 col3 col1 col2 col1 col1 col2 col2 col3 col3 col3 col2
0  4_1  4_3  1_1  4_2  2_1  3_1  1_2  3_2  1_3  3_3  2_3  2_2

或者,如果只打乱 df,您可以这样做:

dfs = [df1, df2, df3, df4]
random.shuffle(dfs)
pd.concat(dfs, axis=1)

Out[133]: 
  col1 col2 col3 col1 col2 col3 col1 col2 col3 col1 col2 col3
0  4_1  4_2  4_3  2_1  2_2  2_3  1_1  1_2  1_3  3_1  3_2  3_3

关于python - 按行随机连接数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38506360/

相关文章:

Python - 如何合并一个 df 中的列值以匹配另一个 df 中的行?

python - 如何使用 numpy 或 pandas 仅在 python 中的两行之间读取数据?

python - 二维 numpy 数组的所有可能组合

python - 高效的概率树分支

python - 匹配 Pandas 中字符和数字的混合

python - 如何从 Pandas 数据框值中计算特定日期间隔内的值数?

python - Pandas - 匹配两个数据框中的两列并在 df1 中创建新列

python - 如何在 re.sub 中索引组元素?

python - 如何查找字符串的开头和结尾

python - 计算多维 numpy 数组元素的内部点积