Dra*_*ago 3 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"]})
Run Code Online (Sandbox Code Playgroud)
我怎样才能连接这四个数据帧随机输出这样的东西(它们是随机合并的行):
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
Run Code Online (Sandbox Code Playgroud)
我想我可以做这样的事情:
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
Run Code Online (Sandbox Code Playgroud)
上面的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
Run Code Online (Sandbox Code Playgroud)
也许是这样的?
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
Run Code Online (Sandbox Code Playgroud)
或者,如果只需要对 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
Run Code Online (Sandbox Code Playgroud)