Apply function to pandas row-row cross product
You also can use pd.DataFrame constructor with apply
:
pd.DataFrame(index=df2.squeeze(), columns=df1.squeeze()).apply(lambda x: x.name.astype(str)+':'+x.index)
Output:
1 2 3 4
one 1:one 2:one 3:one 4:one
two 1:two 2:two 3:two 4:two
three 1:three 2:three 3:three 4:three
four 1:four 2:four 3:four 4:four
Explanation:
First, with pd.DataFrame constructor, first build and empty dataframe with index and columns defined from df2 and df1 respectively. Using pd.DataFrame.squeeze
, we convert those single column dataframes into a pd.Series.
Next, using pd.DataFrame.apply
, we can apply a lambda function which adds the strings from the column name with a colon and the dataframe index for each column of the dataframe.
This yeilds a new dataframe with indexing and desired values.
Let us try np.add.outer
df = pd.DataFrame(np.add.outer(df1[0].astype(str).values,':'+df2[0].values).T)
Out[258]:
0 1 2 3
0 1:one 2:one 3:one 4:one
1 1:two 2:two 3:two 4:two
2 1:three 2:three 3:three 4:three
3 1:four 2:four 3:four 4:four