pandas某些行数据帧合并

时间:2017-05-12 08:56:43

标签: python pandas dataframe merge

print(ScimEn.head(20))
    Rank             Country
0      1               China
1      2       United States
2      3               Japan
3      4      United Kingdom
4      5  Russian Federation
5      6              Canada
6      7             Germany
7      8               India
8      9              France
9     10         South Korea
10    11               Italy
11    12               Spain
12    13                Iran
13    14           Australia
14    15              Brazil
15    16              Taiwan
16    17              Turkey
17    18              Norway
18    19         Netherlands
19    20              Sweden

我想将此DF合并到另一个但仅排列为[0:15]的行。 如果我经常做:

dfs = [ScimEn, energy, GDP[year].reset_index()]
newdf = reduce(lambda left, right: pd.merge(left, right, on='Country'), dfs)
newdf = newdf.set_index('Country')
print(len(newdf))

我有一个包含140个条目的DF,但我想在上面提到的每个排名中有一个包含15个条目的DF。 我也试过了:

 dfs = [ScimEn.where(ScimEn['Rank'] < 15), energy, GDP[year].reset_index()]
newdf = reduce(lambda left, right: pd.merge(left, right, on='Country'), dfs)
newdf = newdf.set_index('Country')
print(len(newdf))

但它只返回了4个条目。

1 个答案:

答案 0 :(得分:1)

我认为您可以按query过滤:

dfs = [ScimEn.query("Rank < 15"), energy, GDP[year].reset_index()]
newdf = reduce(lambda left, right: pd.merge(left, right, on='Country'), dfs)
newdf = newdf.set_index('Country')
print(len(newdf))

boolean indexing提到Phong Phung comment

dfs = [ScimEn[ScimEn['Rank'] < 15], energy, GDP[year].reset_index()]
newdf = reduce(lambda left, right: pd.merge(left, right, on='Country'), dfs)
newdf = newdf.set_index('Country')
print(len(newdf))