簡體   English   中英

Python / Pandas迭代列

[英]Python/Pandas Iterating through columns

我有一個看起來像這樣的DataFrame(有很多額外的列)

          age1     age2      age3     age 4   \
Id#     
1001         5        6         2          8  
1002         7        6         1          0
1003        10        9         7          5
1004         9       12         5          9 

我正在嘗試編寫一個循環,將每個列與之前的列相加並將其返回到新的DataFrame。 我已經開始了,簡單地說,這個:

New = pd.DataFrame()
New[0] = SFH2.ix[:,0]
for x in SFH2:
    ls = [x,x+1]
    B = SFH2[ls].sum(axis=1)
    New[x] = B

print(New)  

而我得到的錯誤是

    ls = [x,x+1]

TypeError: Can't convert 'int' object to str implicitly

我知道int和str是不同的對象,但是我怎樣才能克服這個問題,或者有不同的方法來迭代列? 謝謝!

您可以使用addshift ED DataFrame

print (df.shift(-1,axis=1))
      age1  age2  age3  age4
Id#                         
1001   6.0   2.0   8.0   NaN
1002   6.0   1.0   0.0   NaN
1003   9.0   7.0   5.0   NaN
1004  12.0   5.0   9.0   NaN

print (df.add(df.shift(-1,axis=1), fill_value=0))
      age1  age2  age3  age4
Id#                         
1001  11.0   8.0  10.0   8.0
1002  13.0   7.0   1.0   0.0
1003  19.0  16.0  12.0   5.0
1004  21.0  17.0  14.0   9.0

如果需要換班1 (默認參數,省略):

print (df.shift(axis=1))
      age1  age2  age3  age4
Id#                         
1001   NaN   5.0   6.0   2.0
1002   NaN   7.0   6.0   1.0
1003   NaN  10.0   9.0   7.0
1004   NaN   9.0  12.0   5.0

print (df.add(df.shift(axis=1), fill_value=0))
      age1  age2  age3  age4
Id#                         
1001   5.0  11.0   8.0  10.0
1002   7.0  13.0   7.0   1.0
1003  10.0  19.0  16.0  12.0
1004   9.0  21.0  17.0  14.0

這聽起來像你正在尋找的cumsum

In [5]: df
Out[5]: 
      age1  age2  age3  age4
Id#                         
1001     5     6     2     8
1002     7     6     1     0
1003    10     9     7     5
1004     9    12     5     9

In [6]: df.cumsum(axis=1)
Out[6]: 
      age1  age2  age3  age4
Id#                         
1001     5    11    13    21
1002     7    13    14    14
1003    10    19    26    31
1004     9    21    26    35

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM