2017-02-27 59 views
2

複製必須爲'城市'列'BH'開始。 複製的df.index shouls是跟原來一樣 EG -從現有的熊貓數據框中複製一些行到一個新的

   STATE   CITY 
315   KA    BLR 
423   WB    CCU 
554   KA    BHU 
557   TN    BHY 

# state_df is new dataframe, df is existing 
state_df = pd.DataFrame(columns=['STATE', 'CITY'])  
for index, row in df.iterrows(): 
    city = row['CITY'] 

    if(city.startswith('BH')): 
     append row from df to state_df # pseudocode 

作爲新熊貓和Python,我需要幫助的僞代碼的最有效方式。

回答

0

解決方案與startswithboolean indexing

print (df['CITY'].str.startswith('BH')) 
315 False 
423 False 
554  True 
557  True 

state_df = df[df['CITY'].str.startswith('BH')] 
print (state_df) 
    STATE CITY 
554 KA BHU 
557 TN BHY 

如果需要拷貝僅一些列添加loc

state_df = df.loc[df['CITY'].str.startswith('BH'), ['STATE']] 
print (state_df) 
    STATE 
554 KA 
557 TN 

時序

#len (df) = 400k 
df = pd.concat([df]*100000).reset_index(drop=True) 


In [111]: %timeit (df.CITY.str.startswith('BH')) 
10 loops, best of 3: 151 ms per loop 

In [112]: %timeit (df.CITY.str.contains('^BH')) 
1 loop, best of 3: 254 ms per loop 
2

試試這個:

In [4]: new = df[df['CITY'].str.contains(r'^BH')].copy() 

In [5]: new 
Out[5]: 
    STATE CITY 
554 KA BHU 
557 TN BHY 

如果我需要複製唯一行的某些列,而不是整個 行

cols_to_copy = ['STATE'] 
new = df.loc[df.CITY.str.contains(r'^BH'), cols_to_copy].copy() 

In [7]: new 
Out[7]: 
    STATE 
554 KA 
557 TN 
+0

使用for循環,代碼爲state_df = state_df.append(row)。但是你的解決方案不需要循環,對吧?如果我只需要複製行的一些列而不是整行,該怎麼辦? – kakoli

+0

@kakoli,我已經添加了另一個例子 – MaxU

0

刪除了for循環,最後寫了: state_df = df.loc [DF ['CTYNAME '] .str.startswith('Washington'),cols_to_copy]

For循環可能會比較慢,但需要檢查一下,

相關問題