基于另一个DataFrame更新DataFrame

时间:2014-02-25 22:22:34

标签: python pandas dataframe

鉴于DataFrame df

    Id Sex  Group  Time  Time!
0  21   M      2  2.31    NaN
1   2   F      2  2.29    NaN

update

    Id Sex  Group  Time
0  21   M      2  2.36
1   2   F      2  2.09
2   3   F      1  1.79

我想在IdSexGroup上进行匹配,并使用Time!值更新Time(来自update df)如果匹配,或插入新记录。

我是这样做的:

df = df.set_index(['Id', 'Sex', 'Group'])
update = update.set_index(['Id', 'Sex', 'Group'])

for i, row in update.iterrows():
    if i in df.index:  # update
        df.ix[i, 'Time!'] = row['Time']
    else:              # insert new record
        cols = up.columns.values 
        row = np.array(row).reshape(1, len(row))
        _ = pd.DataFrame(row, index=[i], columns=cols)
       df = df.append(_)

print df

              Time  Time!
Id Sex Group             
21 M   2      2.31   2.36
2  F   2      2.29   2.09
3  F   1      1.79    NaN

代码似乎有效,我希望的结果与上述相符。但是,我注意到在大数据集上使用条件

时会出现这种情况
if i in df.index:
    ...
else:
    ...

工作显然是错误的(它会进入else而反之亦然,我猜,这个MultiIndex可能是某种原因的原因)。

所以我的问题是,你知道任何其他方式,或者我的更强大的版本,根据另一个df更新一个df?

1 个答案:

答案 0 :(得分:3)

我想我会通过合并执行此操作,然后使用where更新列。首先从上方删除时间列:

In [11]: times = up.pop('Time')  # up = the update DataFrame

In [12]: df1 = df.merge(up, how='outer')

In [13]: df1
Out[13]:
   Id Sex  Group  Time  Time!
0  21   M      2  2.31    NaN
1   2   F      2  2.29    NaN
2   3   F      1   NaN    NaN

更新时间,如果它不是NaN和时间!如果它是NaN:

In [14]: df1['Time!'] = df1['Time'].where(df1['Time'].isnull(), times)

In [15]: df1['Time'] = df1['Time'].where(df1['Time'].notnull(), times)

In [16]: df1
Out[16]:
   Id Sex  Group  Time  Time!
0  21   M      2  2.31   2.36
1   2   F      2  2.29   2.09
2   3   F      1  1.79    NaN
相关问题