【问题标题】:Pandas JOIN/MERGE/CONCAT Data Frame On Specific IndicesPandas JOIN/MERGE/CONCAT Dataframe 在特定索引上
【发布时间】:2019-10-18 06:51:53
【问题描述】:

我想根据我创建的地图 (dictionary) 加入两个特定于数据框的索引。有什么有效的方法来做到这一点?

数据:

df = pd.DataFrame({"a":[10, 34, 24, 40, 56, 44], 
                    "b":[95, 63, 74, 85, 56, 43]}) 

print(df)

    a   b
0  10  95
1  34  63
2  24  74
3  40  85
4  56  56
5  44  43


df1 = pd.DataFrame({"c":[1, 2, 3, 4], 
                   "d":[5, 6, 7, 8]}) 

print(df1)
   c  d
0  1  5
1  2  6
2  3  7
3  4  8

d = { 
    (1,0):0.67,
    (1,2):0.9,
    (2,1):0.2,
    (2,3):0.34
    (4,0):0.7,
    (4,2):0.5
}

所需的输出:

  a  b  c  d  ratio
0 34 63 1  5  0.67
1 34 63 3  7  0.9
...
5 56 56 3  7  0.5

我能够做到这一点,但是这需要很长时间,因为我的原始数据框的地图有大约 470 万行要映射。我很想知道是否有办法将MERGEJOINCONCAT 这些数据帧放在不同的索引上。

我的方法:

matched_rows = []
for key in d.keys():                                              
    s = df.iloc[key[0]].tolist() + df1.iloc[key[1]].tolist() + [d[key]]
    matched_rows.append(s)

df_matched = pd.DataFrame(matched_rows, columns = df.columns.tolist() + df1.columns.tolist() + ['ratio']

非常感谢您的帮助。提前非常感谢。

【问题讨论】:

    标签: python-3.x pandas data-structures


    【解决方案1】:

    创建Series,然后由dictioanryDataFrame.join 创建DaatFrame,最后按位置删除前两列:

    df = (pd.Series(d).reset_index(name='ratio')
            .join(df, on='level_0')
            .join(df1, on='level_1')
            .iloc[:, 2:])
    print (df)
       ratio   a   b  c  d
    0   0.67  34  63  1  5
    1   0.90  34  63  3  7
    2   0.20  24  74  2  6
    3   0.34  24  74  4  8
    4   0.70  56  56  1  5
    5   0.50  56  56  3  7
    

    然后在必要时重新排列列:

    df = df[df.columns[1:].tolist() + df.columns[:1].tolist()]
    print (df)
        a   b  c  d  ratio
    0  34  63  1  5   0.67
    1  34  63  3  7   0.90
    2  24  74  2  6   0.20
    3  24  74  4  8   0.34
    4  56  56  1  5   0.70
    5  56  56  3  7   0.50
    

    【讨论】:

    • 这太棒了。非常感谢,@jezrael。顺便说一句,你能解释一下吗?两个不同的指数是如何结合起来的?我会接受你的回答。
    • @KrishnangKDalal - 它并行工作 - 首先由 df 加入,然后由 df1 加入 - 不是同时由两者加入。所以首先将它通过转换为列level_0 的元组的第一个值加入,然后通过pd.Series(d).reset_index(name='ratio') 转换为level_1 的元组的第二个值加入
    • 知道了。所以,pd.Series(d).reset_index(name='ratio') 似乎起到了主胶的作用,对吧?
    • @KrishnangKDalal - 完全正确。
    猜你喜欢
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    相关资源
    最近更新 更多