繁体   English   中英

索引不匹配时更新pandas数据帧的最有效方法

[英]most efficient way to update pandas dataframe when index not match

我有两个pandas DataFrames,我想用另一个更新一个...但我不能确定索引是否匹配。 (所以使用DataFrame.update是个问题!)

〔实施例:

import pandas as pd
df1 = pd.DataFrame([('path1', 0, 0, 0),
                    ('path2', 0, 0, 0),
                    ('path3', 0, 0, 0),
                    ('path4', 0, 0, 0),],
                  columns=['path', 'class', 'manual', 'conf'],
                  index = [1,2,3,4])

df2 = pd.DataFrame([('path1', 1, 0, 0),
                    ('path2', 0, 1, 0),
                    ('path3', 0, 0, 1),
                    ('path5', 1, 1, 0),
                    ('path6', 1, 1, 0),],
                  columns=['path', 'class', 'manual', 'conf'],
                  index = [10,11,12,13,14])

期望的结果:

update_annotations(df1, df2)

    path  class  manual  conf
1  path1      1       0     0
2  path2      0       1     0
3  path3      0       0     1
4  path4      0       0     0

df1.update(df2)可能存在风险,因为这些数据帧的索引可能不匹配。 这样做最安全,最有效的方法是什么?

快速而肮脏

df1[['path']].merge(df2, 'left')

    path  class  manual  conf
0  path1    1.0     0.0   0.0
1  path2    0.0     1.0   0.0
2  path3    0.0     0.0   1.0
3  path4    NaN     NaN   NaN

更快,更少脏

df1[['path']].merge(df2, 'left').fillna(0).astype(df1.dtypes)

    path  class  manual  conf
0  path1      1       0     0
1  path2      0       1     0
2  path3      0       0     1
3  path4      0       0     0

df1填充NaN

df1[['path']].merge(df2, 'left').fillna({**df1}).astype(df1.dtypes)

    path  class  manual  conf
0  path1      1       0     0
1  path2      0       1     0
2  path3      0       0     1
3  path4      0       0     0

每个克里斯

df1.set_index('path').assign(**df2.set_index('path')).reset_index()

    path  class  manual  conf
0  path1    1.0     0.0   0.0
1  path2    0.0     1.0   0.0
2  path3    0.0     0.0   1.0
3  path4    NaN     NaN   NaN

保留索引

由于订单保证相同,我们可以使用set_index

df1[['path']].merge(df2, 'left').fillna({**df1}).astype(df1.dtypes).set_index(df1.index)

    path  class  manual  conf
1  path1      1       0     0
2  path2      0       1     0
3  path3      0       0     1
4  path4      0       0     0

根据piRSquared的答案,我正在寻找答案:

df1 = (df1[['path']]
       .merge(df2, 'left')
       .set_index(df1.index)
       .fillna(df1))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM