Python:尝试交叉应用两个数据框

标签 python pandas dataframe apply

<分区>

我正在尝试获取一个数据框,该数据框包含两个不同数据框中两个单独列的所有组合。我的数据框如下所示:

>>>first_df                          >>>second_df
    id test                                id text   
 0   1  abc                              0 11  uvw
 1   2  def                              1 22  xyz 
 2   3  ghi

据此,我能够使用这种方法获得组合:

df = pd.DataFrame(list(itertools.product(list(a['test']),list(b['text']))),columns=['test','text'])
>>>df
    test text
 0  abc  uvw
 1  abc  xyz
 2  def  uvw
 3  def  xyz
 4  ghi  uvw
 5  ghi  xyz

我无法理解的是,如何将相关的 id 列也放入我的数据框中,使其看起来像:

>>>df
    id test text kid
 0   1 abc  uvw   11
 1   1 abc  xyz   22
 2   2 def  uvw   11
 3   2 def  xyz   22
 4   3 ghi  uvw   11
 5   3 ghi  xyz   22

我尝试分别对 id 列进行组合

df1 =pd.DataFrame(list(itertools.product(list(a['id']),list(a['id']))),columns=['id','id'])
df
   id    id
0   1     1
1   1     2
2   1     3
3   2     1
4   2     2
5   2     3
6   3     1
7   3     2
8   3     3

df2 =pd.DataFrame(list(itertools.product(list(b['kid']),list(b['kid']))),columns=['kid','kid'])
>>>df2
   id  kid
0  11   11
1  11   22
2  22   11
3  22   22

然后我尝试连接...这显然失败了

df = pd.concat([df['id'],df2,df1['kid']],axis=1)

>>> df
   id test text   kid
0   1  abc  uvw  11.0
1   1  abc  xyz  22.0
2   1  def  uvw  11.0
3   2  def  xyz  22.0
4   2  ghi  uvw   NaN
5   2  ghi  xyz   NaN
6   3  NaN  NaN   NaN
7   3  NaN  NaN   NaN
8   3  NaN  NaN   NaN

我觉得我可以使用数据帧的 apply 函数来解决这个问题,但我不知道如何解决。任何线索将不胜感激。感谢您阅读这么多:)

最佳答案

您可以将交叉连接与 merge 结合使用和具有相同常量的新辅助列:

first_df['tmp'] = 1
second_df['tmp'] = 1

df = pd.merge(first_df, second_df.rename(columns={'id':'kid'}), on='tmp').drop('tmp',1)
print (df)
   id test  kid text
0   1  abc   11  uvw
1   1  abc   22  xyz
2   2  def   11  uvw
3   2  def   22  xyz
4   3  ghi   11  uvw
5   3  ghi   22  xyz

使用 assign 的一行解决方案对于新列:

df = pd.merge(first_df.assign(tmp=1), 
              second_df.assign(tmp=1).rename(columns={'id':'kid'}), on='tmp').drop('tmp',1)
print (df)
   id test  kid text
0   1  abc   11  uvw
1   1  abc   22  xyz
2   2  def   11  uvw
3   2  def   22  xyz
4   3  ghi   11  uvw
5   3  ghi   22  xyz

关于Python:尝试交叉应用两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45905439/

相关文章:

python - 是否可以创建一个类,其每个实例都有不同的类型?

python - Pandas .apply() : How to use a formula in apply() that involves values from preceding cells in the same column?

python - 如何将 pandas DataFrame 中的列取消嵌套(分解)为多行

python Pandas : fluent setter for DataFrame index?

python - 仅在 Spyder IDE 中出现内存错误

python - 如何使用 Celery、RabbitMQ 和 Django 确保每个用户的任务执行顺序?

python - 分配给 for 循环值

python - 如何正确设置 pandas.Dataframe 中特定单元格的值?

python - 大型数据集的零值完整 Pandas 数据框

python - 根据列值删除数据框中的行