我有一个 Pandas DataFrame,长这样:
我想创建一个像这样的 Pandas DataFrame:
df = pd.DataFrame({'col1': [1, 2, 3],
'col2': [4, 5, 6],
'col3': [7, 8, 9]})
df
col1 col2 col3
0 1 4 7
1 2 5 8
2 3 6 9
我想创建一个像这样的 Pandas DataFrame:
df_new
col1 col2 col3
0 1 4 7
1 1 5 8
2 1 6 9
3 2 4 7
4 2 5 8
5 2 6 9
6 3 4 7
7 3 5 8
8 3 6 9
有没有内置的或内置 Pandas 方法的组合可以实现这一点?
即使在 df
中存在重复项,我也希望输出具有相同的格式。换句话说:
df
col1 col2 col3
0 1 4 7
1 2 5 8
2 2 6 8
df_new
col1 col2 col3
0 1 4 7
1 1 5 8
2 1 6 8
3 2 4 7
4 2 5 8
5 2 6 8
6 2 4 7
7 2 5 8
8 2 6 8
df[['col1']].merge(df[['col2', 'col3']], how='cross').reset_index(drop=True)
。这是正确的吗?还是根据列值或其他方式需要固定次数地扩展DataFrame? - Henry Eckerhow='cross'
!它也可以是to_tile=['col1']; df[to_tile].merge(df[df.columns.difference(to_tile)], how='cross').reset_index(drop=True)
。 - Corralien