2017-12-27 1284 views
9

給定一個包含多列的DataFrame,我們如何從特定列中逐行選擇值來創建新的Series?熊貓:從行的特定列中選擇值

df = pd.DataFrame({"A":[1,2,3,4], 
        "B":[10,20,30,40], 
        "C":[100,200,300,400]}) 
columns_to_select = ["B", "A", "A", "C"] 

目標: [10, 2, 3, 400]

一個方法,工作原理是利用一個適用的語句。

df["cols"] = columns_to_select 
df.apply(lambda x: x[x.cols], axis=1) 

不幸的是,這不是一個矢量化操作,需要很長時間處理大型數據集。任何想法,將不勝感激。

回答

10

Pandas approach

In [22]: df['new'] = df.lookup(df.index, columns_to_select) 

In [23]: df 
Out[23]: 
    A B C new 
0 1 10 100 10 
1 2 20 200 2 
2 3 30 300 3 
3 4 40 400 400 
+1

一個你身後秒。 ;-) – Wen

+0

@溫,是的,我知道這種感覺 - 對不起:) – MaxU

+0

@MaxU這正是我所期待的。謝謝! –

8

NumPy的方式

下面是使用advanced indexing一個矢量NumPy的方式 -

# Extract array data 
In [10]: a = df.values 

# Get integer based column IDs 
In [11]: col_idx = np.searchsorted(df.columns, columns_to_select) 

# Use NumPy's advanced indexing to extract relevant elem per row 
In [12]: a[np.arange(len(col_idx)), col_idx] 
Out[12]: array([ 10, 2, 3, 400]) 

如果df列名不排序,我們需要使用sorter大吵np.searchsorted。該代碼提取col_idx,例如通用df是:

# https://stackoverflow.com/a/38489403/ @Divakar 
def column_index(df, query_cols): 
    cols = df.columns.values 
    sidx = np.argsort(cols) 
    return sidx[np.searchsorted(cols,query_cols,sorter=sidx)] 

所以,col_idx會像這樣獲得 -

col_idx = column_index(df, columns_to_select) 

進一步優化

剖析它揭示了瓶頸正在處理字符串np.searchsorted,通常NumPy的弱點與字符串沒有太大關係。所以,爲了克服這個問題,並使用列名爲單個字母的特殊情況,我們可以快速將它們轉換爲數字,然後將它們提供給searchsorted以加快處理速度。

因此,獲得基於整數列ID,對於列名的單字母排序的情況的優化版本,將是 -

def column_index_singlechar_sorted(df, query_cols): 
    c0 = np.fromstring(''.join(df.columns), dtype=np.uint8) 
    c1 = np.fromstring(''.join(query_cols), dtype=np.uint8) 
    return np.searchsorted(c0, c1) 

這給了我們解決方案的修改版,像這樣 -

計時 -

In [149]: # Setup df with 26 uppercase column letters and many rows 
    ...: import string 
    ...: df = pd.DataFrame(np.random.randint(0,9,(1000000,26))) 
    ...: s = list(string.uppercase[:df.shape[1]]) 
    ...: df.columns = s 
    ...: idx = np.random.randint(0,df.shape[1],len(df)) 
    ...: columns_to_select = np.take(s, idx).tolist() 

# With df.lookup from @MaxU's soln 
In [150]: %timeit pd.Series(df.lookup(df.index, columns_to_select)) 
10 loops, best of 3: 76.7 ms per loop 

# With proposed one from this soln 
In [151]: %%timeit 
    ...: a = df.values 
    ...: col_idx = column_index_singlechar_sorted(df, columns_to_select) 
    ...: out = pd.Series(a[np.arange(len(col_idx)), col_idx]) 
10 loops, best of 3: 59 ms per loop 

鑑於df.lookup解決了一般情況,這可能是一個更好的選擇,但其他可能的優化,如這篇文章中所示,也可以很方便!