I have a df like this.
Date
2022-10-22
2022-10-21
2022-10-20
I want to combine and duplicate for each element in this list
['NAB', 'CBA']
To get a result df like this.
Date Bank
2022-10-22 NAB
2022-10-22 CBA
2022-10-21 NAB
2022-10-21 CBA
2022-10-20 NAB
2022-10-20 CBA
Thanks in advance.
CodePudding user response:
Add fixed Bank=["NAB", "CBA"] column to df:
df["Bank"] = df.apply(lambda _: ["NAB", "CBA"], axis=1)
[Out]:
date Bank
0 2022-10-22 [NAB, CBA]
1 2022-10-21 [NAB, CBA]
2 2022-10-20 [NAB, CBA]
Then explode date column:
df = df.explode("Bank")
[Out]:
date Bank
0 2022-10-22 NAB
0 2022-10-22 CBA
1 2022-10-21 NAB
1 2022-10-21 CBA
2 2022-10-20 NAB
2 2022-10-20 CBA
CodePudding user response:
You can use a cross merge
:
lst = ['NAB', 'CBA']
out = df.merge(pd.Series(lst, name='Bank'), how='cross')
Output:
Date Bank
0 2022-10-22 NAB
1 2022-10-22 CBA
2 2022-10-21 NAB
3 2022-10-21 CBA
4 2022-10-20 NAB
5 2022-10-20 CBA