2016-03-30 20 views
3

Pandas veri çerçevesindeki bir sütunun tümüne bir işlev uygulamak istiyorum. Bu fonksiyon, bu sütunda, şu anda verilerin üzerine, ancak bunun yanında başka bir sütunun değeri gerektirir olacaktır göstermek için:Python Panda'larda argüman olarak başka bir sütunu alan bir sütuna bir işlev uygulanması

col 0, col 1, 
23, 'word' 
45, 'word2' 
63, 'word3' 

pandalar içine numarası sütununda yorgun geçen sahip geçerli yöntem:

df[1] = df.apply(retrieve_original_string(df[0]), axis=1) 

sys:1: DtypeWarning: Columns (3,4) have mixed types. Specify dtype option on import or set low_memory=False. 
Traceback (most recent call last): 
    File "/home/noname365/similar_keywords_microsoft/similar_keywords.py", line 95, in <module> 
    merged_df[1] = merged_df.apply(retrieve_original_string(merged_df[0], match_df), axis=1) 
    File "/home/noname365/similar_keywords_microsoft/similar_keywords.py", line 12, in retrieve_original_string 
    row_num = int(row) 
    File "/home/noname365/virtualenvs/env35/lib/python3.5/site-packages/pandas/core/series.py", line 81, in wrapper 
    "cannot convert the series to {0}".format(str(converter))) 
TypeError: cannot convert the series to <class 'int'> 

hata bir satır-by-satır bazında ayrı ayrı işleve tam sayı sütununu geçen yerine olduğumu ima:

Ama bu hata verir. Bunu nasıl başarabilirim?

+0

Muhtemelen 'df [1] = df.apply (lambda satır istiyorum: retrieve_original_string (satır [0]), eksen = 1) ' – EdChum

cevap

2

IIUC ikinci sütununu seçmek için iloc ihtiyaç ve söz EdChum olarak lambda ekleyin:

def retrieve_original_string(x): 
    x = x + 4 
    #add code 
    return x 


df.iloc[:,1] = df.apply(lambda x: retrieve_original_string(x[0]), axis=1) 
print df 
    col 0 col 1 
0  23  27 
1  45  49 
2  63  67 

#if you need new column 
df['a'] = df.apply(lambda x: retrieve_original_string(x[0]), axis=1) 
print df 
    col 0 col 1 a 
0  23 'word' 27 
1  45 'word2' 49 
2  63 'word3' 67 

Veya:

def retrieve_original_string(x): 
    x = x + 4 
    #add code 
    return x 


df.iloc[:,1] = df.iloc[:,0].apply(retrieve_original_string) 
print df 
    col 0 col 1 
0  23  27 
1  45  49 
2  63  67 
İlgili konular