2016-12-01 44 views
2

應用str.lower到熊貓我有以下形式的數據幀DF:通過列表理解

animal fruit 
0 "Dog" "Apple" 
1 "Cat" "Banana" 
2 "Rat" "Grape" 

我想申請str.lower()的所有列(但不是頭)。

這個工程:

for i in df: 
    df[i] = df[i].str.lower() 

我怎麼能寫這個作爲一個列表comphrension?

我想:

df[i] = [df[i].str.lower() for i in df] 

但是,這並不工作,我得到一個:

TypeError: list indices must be integers, not instancemethod 

我必須在列表理解這種內更改什麼工作?其次,是否還有更多的「大熊貓」的做法,一般來說,也許使用pandas.apply()函數?

非常感謝您的幫助。

回答

2

列表理解的輸出是Series的列表。因此,需要concatlist

L = [df[i].str.lower() for i in df] 
print (L) 
[0 dog 
1 cat 
2 rat 
Name: animal, dtype: object, 0  apple 
1 banana 
2  grape 
Name: fruit, dtype: object] 

df1 = pd.concat(L, axis=1) 
print (df1) 
    animal fruit 
0 dog apple 
1 cat banana 
2 rat grape 

解決方案與apply

print (df.apply(lambda x: x.str.lower())) 
    animal fruit 
0 dog apple 
1 cat banana 
2 rat grape 

時序

df = pd.concat([df]*1000).reset_index(drop=True) 
df = pd.concat([df]*1000, axis=1) 
df.columns = range(len(df.columns)) 
#[3000 rows x 2000 columns] 
print (df) 

In [89]: %timeit (pd.concat([df[i].str.lower() for i in df], axis=1)) 
1 loop, best of 3: 2.3 s per loop 

In [90]: %timeit (df.apply(lambda x: x.str.lower())) 
1 loop, best of 3: 2.63 s per loop 

In [91]: %timeit (df.stack().str.lower().unstack()) 
1 loop, best of 3: 5.04 s per loop 
+0

感謝,所以** **的concat將需要以這種方式大熊貓d框架上做任何列表理解? – Chuck

+1

如果需要像'str.lower()'一樣使用'Series'來應用函數,那麼需要concat方法和最快的列表理解。 – jezrael

+0

好的,謝謝。非常感激。 – Chuck

1

可以stack因此,它使一列,然後調用str.lower,然後unstack恢復列回:

In [74]: 
df = df.stack().str.lower().unstack() 
df 

Out[74]: 
    animal fruit 
0 dog apple 
1 cat banana 
2 rat grape 
+0

感謝您的幫助 - 有很多這些功能可以學習。 – Chuck