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个条目。
答案 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))