如何按行随机合并、连接或连接 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/