2017-02-01 98 views
-2

我有一個數據集組織成熊貓數據框。在跳過第一行時遍歷熊貓數據框

下面是數據的一個小例子:

 x142_2012 x126_2012 x156_2012 x167_2012  x1_2012 x243_2012 
0  690.842629 0.005029 51.600000 5.454545 43.000000 27.700000 
1  4247.485437 5.062739 95.400000 54.655959 100.000000 15.700000 
2  5583.616160  NaN 84.900000 15.228027 100.000000 31.600000 
3    NaN  NaN 100.000000  NaN 59.328910  NaN 
4 39666.369210 34.335120 100.000000 86.434425 100.000000 50.000000 
5  5531.776299  NaN 47.800000 16.937210 37.000000 34.100000 
6 13525.616220 14.674017 97.900000 58.000000 90.875440 10.500000 
7  7465.145864 3.196932 85.417850 29.954302 86.270751 14.872018 
8 14357.411590 12.530952 98.600000 55.800000 99.800000 37.400000 
9  3565.517575 7.142042 99.700000 37.500000 100.000000 10.700000 
10   NaN  NaN 98.100000 74.000000 90.875440  NaN 

我想建立一幫其相互變量比較變量x142_2012散點圖,個別。因此,我想遍歷數據框,同時跳過第一個條目。我想這

import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 

for variable in subset[1:]: 
    plt.figure() 
    scatterplot = sns.regplot(x="x142_2012", y=variable, fit_reg=False, data=subset) 

代替輸出5個散點圖(x/y1, x/y2, x/y3, x/y4, x/y5),但是,它輸出6個散點圖與第一個是x/x

我得到解決此問題與此:

for variable in subset: 
    if variable == "x142_2012": 
     continue 
    plt.figure() 
    scatterplot = sns.regplot(x="x142_2012", y=variable, fit_reg=False, data=subset) 

但我不覺得很優雅。我看着Efficient way to do pandas operation and skip row並試圖for variable in subset[x].idx[1:],但它給我AttributeError: 'Series' object has no attribute 'idx'

有沒有更好的方法來做到這一點?

+0

我有問題,瞭解你的數據框的樣子。你能提供一個具有預想結構的數據框的打印輸出,並清楚說明這與'x','y1'等有關嗎? – ImportanceOfBeingErnest

+0

@ImportanceOfBeingErnest我正在使用世界銀行的數據集。我已更新該帖子以包含更多信息。 – Greg

回答

2

相反subset[1:]的,使用subset.columns[1:]

1

subset[1:]選擇除第一行以外的所有行,結果DataFrame仍有六列。

你可以做的反而是遍歷數據幀的列(並離開了第一):

import pandas as pd 
import numpy as np 
import seaborn as sns 
import matplotlib.pyplot as plt 

# generate some data 
a = np.random.rand(10,6) 
a[:,0]= np.arange(10) 
df = pd.DataFrame(a, columns=[l for l in "xabcde"]) 
#print df 

#plot 
for col in df.columns[1:]: 
    plt.figure() 
    scatterplot = sns.regplot(x="x", y=col, fit_reg=False, data=df) 

plt.show()