背景
我有两个样本df
这里是df1
import pandas as pd
l = [list(['ABC', 'DEF', 'GHI'])]
df1 = pd.DataFrame({'Letters': l})
df1
Letters
0 [ABC, DEF, GHI]
还有df2
df2 = pd.DataFrame({'Text' : ['Hi ',
'hey',
'hello ',
'bye',
'see ya'
],
'ID': [1,2,3, 4,5]
})
df2
ID Text
0 1 Hi
1 2 hey
2 3 hello
3 4 bye
4 5 see ya
所需的输出
ID Text Letters
0 1 Hi [ABC, DEF, GHI]
1 2 hey [ABC, DEF, GHI]
2 3 hello [ABC, DEF, GHI]
3 4 bye [ABC, DEF, GHI]
4 5 see ya [ABC, DEF, GHI]
问题
如何复制df1
和df2
并合并以获得所需的输出?
答案 0 :(得分:3)
您可以这样做:
df2=df2.assign(**pd.concat([df1]*len(df2),ignore_index=True))
或者:
df2=df2.assign(Letters=np.resize(df1.to_numpy(),len(df2))) #df1.values for lower versions
Text P_ID Letters
0 Hi 1 [ABC, DEF, GHI]
1 hey 2 [ABC, DEF, GHI]
2 hello 3 [ABC, DEF, GHI]
3 bye 4 [ABC, DEF, GHI]
4 see ya 5 [ABC, DEF, GHI]
答案 1 :(得分:3)
也可以broadcast_to
df2['letters'] = np.broadcast_to(df1['Letters'], len(df2))
Text P_ID letters
0 Hi 1 [ABC, DEF, GHI]
1 hey 2 [ABC, DEF, GHI]
2 hello 3 [ABC, DEF, GHI]
3 bye 4 [ABC, DEF, GHI]
4 see ya 5 [ABC, DEF, GHI]