简体   繁体   中英

Pandas: apply a specific function to columns and create column in new dataframe

I have a dataframe df1 , like this:

date        sentence
29/03/1029  i like you
.....

I want to create new dataframe df2 like this:

date         verb    object
29/03/2019   like    you
....

with the function like this:

def getSplit(df1):
    verbList = []
    objList  = []
    df2 = pd.DataFrame()
    for row in df1['sentence']:
        verb = getVerb(row)
        obj  = getObj(row)
        verbList.append(verb)
        objList.append(obj)
    df2 = df1[[date]].copy
    df2['verb'] = verbList
    df2['object'] = objList
    return df2

my function run well, but it's slow. Could someone help me improve the function so that can run faster?

Thank you

You can Use apply method of pandas to process fast:-

getverb(row):
    pass  # Your function
getobj(row):
    passs # Your function
df2 = df1.copy()  # Making copy of your dataframe.

df2['verb'] = df2['sentence'].apply(getverb)
df2['obj'] = df2['sentence'].apply(getobj)
df2.drop('sentence', axis=1, inplace=True)  # Droping sentence column
df2

I hope it may help you. (accept and upvote answer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM