【问题标题】:How to join these two pandas data frames?如何加入这两个熊猫数据框?
【发布时间】:2013-04-09 06:37:09
【问题描述】:

我无法将 DataFrame1 与 DataFrame2 连接起来,我怀疑这是由于其中一个具有 int64 索引而另一个具有字符串索引。如何将字符串索引也转换为 int64 索引(如果这确实是问题)?如果不是,如何合并这两个数据框?

数据帧1

<class 'pandas.core.frame.DataFrame'>
Int64Index: 9943 entries, 10029934 to 9962359
Data columns:
face_area     9943  non-null values
image_area    9943  non-null values
ratio         9943  non-null values
dtypes: int64(3)

数据帧2

<class 'pandas.core.frame.DataFrame'>
Index: 9412 entries, 10029934 to 9962359
Data columns:
1        9412  non-null values
2        9412  non-null values
name     9412  non-null values
class    9412  non-null values
dtypes: float64(2), int64(1), object(1)

【问题讨论】:

  • 您尝试了什么,结果如何?此外,指数中实际值的性质是什么?第二个只有第一个索引的字符串版本,还是完全不同?
  • 如果您提供带有相应类型的小样本DataFrames 并添加请求的输出,我会更容易。
  • @BrenBam 刚刚找到了一个解决方案,如果您好奇,请在下面发布。

标签: python join dataframe pandas


【解决方案1】:
DataFrame2['id'] = DataFrame2.index.map(int)
DataFrame2.set_index('id')

这似乎已经解决了问题,我现在可以加入了。如果您有更优雅的解决方案,我仍然很乐意听到。

【讨论】:

    【解决方案2】:

    你可以使用astype:

    df.index = df.index.astype(int)
    

    例子:

    In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
    
    In [2]: df2 = pd.DataFrame([[1, 2], [3, 4]], columns=['c', 'd'], index=['0','1'])
    
    In [3]: df2.index = df2.index.astype(int)
    
    In [4]: df1.join(df2)
    Out[4]: 
       a  b  c  d
    0  1  2  1  2
    1  3  4  3  4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多