2014-09-25 64 views
0

在向循環中添加列時,我很難理解Python的Pandas庫的行爲。我想遍歷一個對象列表(這些實際上是日期元組),在每個循環中添加許多列。這方面的一個簡化版本如下:將循環中的列添加到Pandas DataFrame

import pandas as pd 
import numpy as np 

df = pd.DataFrame(np.arange(6).reshape(2, 3), columns=('a', 'b', 'c')) 

for x in range(10): 

    # Printed on each loop: 
    print('Adding column type 1') 
    df['{}_type1'.format(x)] = 'Type 1' 

    # Printed on last loop only: 
    print('Adding column type 2') 
    df['{}_type2'.format(x)] = 'Type 2' 

我希望這20個新列添加到數據幀(每2循環),而是它增加了11列; '1型'的前10個,'2型'的11個。此外,第一打印輸出10次,但第二隻一次:

Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 1 
Adding column type 2 

我是新來的大熊貓可能會缺少一些基本的東西,但是這似乎是在邏輯錯誤對我來說,也許是一個流氓continue那矢量化操作?任何想法或解釋都會受到歡迎。

感謝, 多米尼克

+0

你的代碼適合我,你確定你沒有縮進問題嗎? – EdChum 2014-09-25 13:36:56

+0

感謝您回來如此迅速。你是對的 - 我已經嘗試將它作爲腳本運行,並且工作正常。我應該提到我在iPython中運行它,這一定是導致問題的原因。 – 2014-09-25 13:45:46

+0

我在ipython中運行你的代碼,它工作正常,是否有一些複製和粘貼問題。另外你想在這裏實現什麼 – EdChum 2014-09-25 13:52:14

回答

0

實際上不是一個與大熊貓的問題。上面的場景是通過右鍵將代碼粘貼到iPython中創建的。使用%paste魔術功能(如文檔建議)不會產生此問題。

相關問題