【问题标题】:Simple join of two Data Frames in PandasPandas 中两个数据框的简单连接
【发布时间】:2015-03-30 14:11:53
【问题描述】:

我在一个使用 Pandas 的 Python 程序中有两个数据框。 我是 Pandas 的新手。

每一个都有许多列和行 - 第一个类似于:

   calc_1  calc_2 calc_3
0  34.3   43.1  42.0
2  3.0    4.0   5.0
3  6.1    6.1   6.2
4  4.2    4.3   4.5

第二个类似:

   gender  age 
0  M      25
2  M      27
3  M      27
4  F      36

对于每个整数行索引,第二个数据框中都有一个对应的条目。我想将它们加入到行索引相等的结果数据框中,例如 SQL 中的内连接。

我似乎无法正确理解这一点。将结果追加到我应该拥有的行数的 2 倍。信息来自 CSV。

   calc_1  calc_2 calc_3  gender age
0  34.3   43.1  42.0      M      25
2  3.0    4.0   5.0       M      27
3  6.1    6.1   6.2       M      27
4  4.2    4.3   4.5       F      36

如果可能,我想在加入时保留列顺序。

编辑:

我似乎无法使用合并,因为整数索引没有名称

 pd.merge(df1, df2, on='?????', how='inner')

【问题讨论】:

  • pd.merge(df1, df2, left_index=True, right_index=True, how='inner') 会工作

标签: python pandas dataframe


【解决方案1】:

使用pd.concat 并传递axis=1 以逐列连接:

In [37]:

pd.concat([df,df1], axis=1)
Out[37]:
   calc_1  calc_2  calc_3 gender  age
0    34.3    43.1    42.0      M   25
2     3.0     4.0     5.0      M   27
3     6.1     6.1     6.2      M   27
4     4.2     4.3     4.5      F   36

join:

In [38]:

df.join(df1)
Out[38]:
   calc_1  calc_2  calc_3 gender  age
0    34.3    43.1    42.0      M   25
2     3.0     4.0     5.0      M   27
3     6.1     6.1     6.2      M   27
4     4.2     4.3     4.5      F   36

merge 并设置left_index=Trueright_index=True

In [41]:

df.merge(df1, left_index=True, right_index=True)
Out[41]:
   calc_1  calc_2  calc_3 gender  age
0    34.3    43.1    42.0      M   25
2     3.0     4.0     5.0      M   27
3     6.1     6.1     6.2      M   27
4     4.2     4.3     4.5      F   36

【讨论】:

  • 谢谢。我希望它会这么简单。不错的综合答案。
  • 上述方法在这种情况下有效,因为索引匹配,如果不匹配会更复杂
猜你喜欢
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 2020-09-02
  • 2017-06-08
  • 1970-01-01
  • 2018-09-27
相关资源
最近更新 更多