合并具有相同模式的两个DataFrame

时间:2017-08-28 08:16:16

标签: python pandas

假设您有两个DataFrame

foo = pd.DataFrame([[123,321],[1543,432]], columns=['id','location'])
bar = pd.DataFrame([[123,421],[1543,436]], columns=['location','id'])

您希望合并到一个大表中。但是,由于模式(列)相同,因此在结果表中应添加一个指示“类型”的新列:

    id   location   type
0   123  321        foo
1   1543 432        foo
0   421  123        bar
1   436  1543       bar

目前,我所做的是

foo['type'] = ['foo'] * foo.shape[0]
bar['type'] = ['bar'] * bar.shape[0]
pd.concat([foo,bar])

是否有一些更明智的方法可以做到这一点,特别是避免前两行?

2 个答案:

答案 0 :(得分:1)

下面的Dror是您执行代码和@jezrael方法的结果。

import pandas as pd
foo = pd.DataFrame([[123,321],[1543,432]], columns=['id','location'])
bar = pd.DataFrame([[123,421],[1543,436]], columns=['location','id'])


def f(foo,bar):
    foo['type'] = ['foo'] * foo.shape[0]
    bar['type'] = ['bar'] * bar.shape[0]
    x = pd.concat([foo,bar])
    return x

%timeit xx = f(foo,bar)


>>>1.14 ms ± 5.56 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


def f2(foo,bar):
    pd.concat([foo,bar], keys=('foo','bar'))
    df = pd.concat([foo,bar], keys=('foo','bar')).reset_index(level=0).rename_axis(None).rename(columns={'level_0':'type'})
    return df
%timeit yy = f2(foo,bar)

>>>3.04 ms ± 18.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

似乎你的代码更快。

答案 1 :(得分:0)

您可以将参数gdal_translate -of GTiff -outsize 4096 4096 -projwin -2097152 2097152 -1048576 1048576 -a_srs "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs" Arctic_r05c02.2017235.terra.250m.tif Arctic_r05c02.2017235.terra.250m_output.tif添加到concat - 它会创建keys

MultiIndex

print (pd.concat([foo,bar], keys=('foo','bar'))) id location foo 0 123 321 1 1543 432 bar 0 421 123 1 436 1543 到列使用:

MultiIndex

assign的另一个解决方案:

df = pd.concat([foo,bar], keys=('foo','bar'))
       .reset_index(drop=True, level=1)
       .rename_axis('type')
       .reset_index()
print (df)
  type    id  location
0  foo   123       321
1  foo  1543       432
2  bar   421       123
3  bar   436      1543
相关问题