Re-combining DataFrames

I have a DataFrame df1 and df2:

df1 = pd.DataFrame(['A1','A2']) 
    0
0  A1
1  A2
df2 = pd.DataFrame(pd.date_range('2016-01-01',periods = 2, freq = '1D'))
           0
0 2016-01-01
1 2016-01-02

How can I get this data file?

    0    1
0  A1  2016-01-01
1  A1  2016-01-02
2  A2  2016-01-01
3  A2  2016-01-02
+4
source share
2 answers

You can use itertools:

import itertools as it

pd.DataFrame(list(it.product(df1[0], df2[0])))
    0          1
0  A1 2016-01-01
1  A1 2016-01-02
2  A2 2016-01-01
3  A2 2016-01-02

itertools returns a generator, so you need to convert it to a list before converting it to a DataFrame

it.product performs all combinations between two iterable objects, for example:

["".join(i) for i in it.product("ABC", "ABC")]
['AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC']
+4
source

You must use pandas.concatto expand your data and then combine it.

import pandas as pd
# test data
df1 = pd.DataFrame(['A1','A2']) 
df2 = pd.DataFrame(pd.date_range('2016-01-01',periods = 2, freq = '1D'))

# expand dataframes to cover all varinats and get the same lengths
df3 = pd.concat([df1]*len(df2), ignore_index=True)
df4 = pd.concat([df2]*len(df2), ignore_index=True)

# final concat to merge dataframes
print (pd.concat([df3,df4],axis=1, ignore_index=True))

Conclusion:

    0          1
0  A1 2016-01-01
1  A2 2016-01-02
2  A1 2016-01-01
3  A2 2016-01-02
+2
source

Source: https://habr.com/ru/post/1673404/


All Articles