2017-10-01 2 views
1

Betrachten Sie den folgenden CodeOneliner zu String-Spalte aus mehreren Spalten

import pandas as pd 
df = pd.DataFrame({'col_1' : [1, 2, 3, 4],\ 
        'col_2' : ['a', 'b', 'c', 'd'],\ 
        'col_3' : ['hey', 'ho', 'banana', 'go']}) 

col = df['col_1'].astype(str) + '_' + \ 
     df['col_2'].astype(str) + '_' + \ 
     df['col_3'].astype(str) 

col 
Out[12]: 
0  1_a_hey 
1  2_b_ho 
2 3_c_banana 
3  4_d_go 
dtype: object 

Kann jemand denken Sie an einen oneliner Herstellung col mit dem Array col_names = ['col_1', 'col_2', 'col_3'] als Eingabe erstellen?

die col_sum = something_smart(col_names)

ist Und natürlich, wenn zum Beispiel different_col_set = ['col_2', 'col_3']

something_smart(different_col_set) 
Out[13]: 
0   a_hey 
1   b_ho 
2  c_banana 
3   d_go 
dtype: object 

Der Punkt ist wirklich, dass col_names ist ein Array beliebige Teilmengen der Spaltennamen der Datenrahmen enthält.

Antwort

2

Option 1]apply Verwenden Sie konnte '_'.join

In [5521]: df[col_names].astype(str).apply('_'.join, axis=1) 
Out[5521]: 
0  1_a_hey 
1  2_b_ho 
2 3_c_banana 
3  4_d_go 
dtype: object 

und

In [5523]: df[different_col_set].astype(str).apply('_'.join, axis=1) 
Out[5523]: 
0  a_hey 
1  b_ho 
2 c_banana 
3  d_go 
dtype: object 

Option 2]reduce Verwendung ist schneller als in diesem Fall keine Anwendung.

In [5527]: reduce(lambda x, y: x + '_' + y, [df[c].astype(str) for c in col_names]) 
Out[5527]: 
0  1_a_hey 
1  2_b_ho 
2 3_c_banana 
3  4_d_go 
dtype: object 

In [5528]: reduce(lambda x, y: x + '_' + y, [df[c].astype(str) for c in different_col_set]) 
Out[5528]: 
0  a_hey 
1  b_ho 
2 c_banana 
3  d_go 
dtype: object 

die zu reduce(lambda x, y: x.astype(str) + '_' +y.astype(str), [df[x] for x in col_names]) ähnlich ist


Timings

In [5556]: df.shape 
Out[5556]: (10000, 3) 

In [5553]: %timeit reduce(lambda x, y: x + '_' + y, [df[c].astype(str) for c in col_names]) 
10 loops, best of 3: 21.7 ms per loop 

In [5554]: %timeit reduce(lambda x, y: x.astype(str) + '_' +y.astype(str), [df[x] for x in col_names]) 
10 loops, best of 3: 22.3 ms per loop 

In [5555]: %timeit df[col_names].astype(str).apply('_'.join, axis=1) 
1 loop, best of 3: 254 ms per loop 
+0

Wirklich schnell ein – Dark

+0

Excellent :) wie ein Charme. Vielen Dank. Ich werde Ihre Antwort in 9 Minuten akzeptieren. – mortysporty

+0

'könnte schneller sein. - Ich glaube, dass Sie Zeitangaben hinzufügen;) – jezrael

Verwandte Themen