重複

2017-10-14 16 views
0

でシリーズを使用して、新しい変数を作成するので、私は出力されたデータセットがあります。重複

gdp = pd.read_csv(r"gdpproject.csv", 
encoding="ISO-8859-1") 
gdp.head(2) 
gdp.tail(2) 

これは私の出力できます:だから、すぐにあなたがその国ごとに気づく

Country.Name Indicator.Name 2004 2005  
0 World GDP 5.590000e+13 5.810000e+13 
1 World Health 5.590000e+13 5.810000e+13 
086 Zimbabwe GDP per capita 8.681564e+02 8.082944e+02 
089 Zimbabwe Population 1.277751e+07 1.294003e+07 

を複数の指標があります。

私がしようとしていることは、現在の2つのインジケータから新しいインジケータを作成することです。そして、それぞれのユニークな国のためにそれを作成してください。

for i in series(gdp['Country.Name']): 
gdp['Military Spending'] = 100/gdp['Military percent of GDP'] * 
gdp['GDP'] 

私に、このエラーメッセージが与えている:私はこのシリーズは、仕事を得るにはどうすればよい

NameError         Traceback (most recent call last) 
<ipython-input-37-d817ea1522fc> in <module>() 
----> 1 for i in series(gdp1['Country.Name']): 
    2  gdp1['Military Spending'] = 100/gdp1['Military percent of GDP'] * 
gdp1['GDP'] 

NameError: name 'series' is not defined 

を?私はまた、単にそれを試してみました。

for i in gdp['Country.Name'] 

まだエラーメッセージが表示されます。

お願いします!

答えて

0

あなたが入力Dataframe(あなたの例では、データMilitary percent of GDPがなかったことに注意してください)、次のしているとしましょう:あなたは、その後GDPMilitary percent of GDPため20042005からのデータと補助データフレームdf_gdpdf_mpgdpを作成することができます

>>> gdp 
    Country.Name   Indicator.Name   2004   2005 
0  World      GDP 5.590000e+13 5.810000e+13 
1  World Military percent of GDP 2.100000e+00 2.300000e+00 
2  Zimbabwe      GDP 1.628900e+10 1.700000e+10 
3  Zimbabwe Military percent of GDP 2.000000e+00 2.100000e+00 

をそれぞれ、次に、というMilitary Spendingを含むdf_mspを作成し、最後にその結果を元のDataframeに追加することができます。特定の状況では、予想されるインデックスで計算が確実に行われるように、reset_indexが必要です。

Dataframeがもたらすであろう。最後に出力
import pandas as pd 
gdp = pd.DataFrame([ 
["World", "GDP", 5.590000e+13, 5.810000e+13], 
["World", "Military percent of GDP", 2.1, 2.3], 
["Zimbabwe", "GDP", 16289e6, 17000e6], 
["Zimbabwe", "Military percent of GDP", 2, 2.1]]) 
gdp.columns = ["Country.Name", "Indicator.Name", "2004", "2005"] 

df_gdp = gdp[gdp["Indicator.Name"] == "GDP"] 
df_mpgdp = gdp[gdp["Indicator.Name"] == "Military percent of GDP"] 

df_msp = pd.DataFrame() 
df_msp["Country.Name"] = df_gdp["Country.Name"].reset_index(drop=True) 
df_msp["Indicator.Name"] = "Military Spending" 
df_msp["2004"] = 100/df_mpgdp[["2004"]].reset_index(drop=True) * df_gdp[["2004"]].reset_index(drop=True) 
df_msp["2005"] = 100/df_mpgdp[["2005"]].reset_index(drop=True) * df_gdp[["2005"]].reset_index(drop=True) 

gdp_out = gdp.append(df_msp) 
gdp_out = gdp_out.sort_values(["Country.Name", "Indicator.Name"]) 
gdp_out = gdp_out.reset_index(drop=True) 

>>> gdp_out 
    Country.Name   Indicator.Name   2004   2005 
0  World      GDP 5.590000e+13 5.810000e+13 
1  World  Military Spending 2.661905e+15 2.526087e+15 
2  World Military percent of GDP 2.100000e+00 2.300000e+00 
3  Zimbabwe      GDP 1.628900e+10 1.700000e+10 
4  Zimbabwe  Military Spending 8.144500e+11 8.095238e+11 
5  Zimbabwe Military percent of GDP 2.000000e+00 2.100000e+00 
コードの下

は、あなたが目指しているもののために働く必要があります