我有以下 df:
df = pd.DataFrame({'A': ['foo', 'bar', 'dex', 'tru'],
'B': ['abc', 'def', 'ghi', 'jkl']})
看起来像:
A
0 foo
1 bar
2 dex
3 tru
我还有以下列表:
block_number = [1000, 2000]
我想要以下输出new_df
:
df = pd.DataFrame({'A': ['foo', 'bar', 'dex', 'tru', 'foo', 'bar', 'dex', 'tru'],
'B': ['abc', 'def', 'ghi', 'jkl', 'abc', 'def', 'ghi', 'jkl'],
'block_number': [1000, 1000, 1000, 1000, 2000, 2000, 2000, 2000]})
看起来像:
A B block_number
0 foo abc 1000
1 bar def 1000
2 dex ghi 1000
3 tru jkl 1000
4 foo abc 2000
5 bar def 2000
6 dex ghi 2000
7 tru jkl 2000
我基本上需要在 df
上的每行中包含 my_list
中的每个项目,但对列表中的所有不同项目都这样做。
from itertools import product
df_out = pd.DataFrame(
product(df.A, block_number), columns=["A", "block_number"]
).sort_values(by="block_number")
print(df_out)
来自 Andrej,地址:Multiply and repeat every row of df by n-item list只为我提供单列 df 的正确结果。如果我的 df 有 2 个或更多(甚至数千列)怎么办?
最佳答案
尝试在pd.concat()
中使用keys参数
(pd.concat([df]*len(block_number),
keys = block_number,
names = ['block_number'])).reset_index(level=0)
输出:
block_number A B
0 1000 foo abc
1 1000 bar def
2 1000 dex ghi
3 1000 tru jkl
0 2000 foo abc
1 2000 bar def
2 2000 dex ghi
3 2000 tru jkl
关于python - 具有多列的 list 和 df 之间的 Itertools 乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74072411/