1
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

I would like to merge this DF to another but only rows which are ranked [0:15]. If I do regular:

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))

I have a DF of 140 entries, but I would like to have a DF of 15 entries per ranking mentioned above. I had also tried:

 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))

But it returned 4 entries only.

2
  • Can you post a sample of the dfs you're trying to merge to? Commented May 12, 2017 at 8:58
  • You could slice the ScimEn dataframe to what you need first then merge normally. ScimEn[ScimEn['Rank'] < 15] will return your needed df. Commented May 12, 2017 at 9:07

1 Answer 1

1

I think you can filter by 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))

Or by boolean indexing as mentioned 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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.