Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply custom function on text on a pandas dataframe rather than iterating individual element

Tags:

python

pandas

My pandas dataframe is very large and so I want to be able to modify the textLower(frame) function so that it gets executed in one command and I dont have to iterate over each row to perform a sequence of string manipulations over each element.

#   Function iterates over all the values of a pandas dataframe
def textLower(frame):
    for index, row in frame.iterrows():
        row['Text'] = row['Text'].lower()
        # further modification on row['Text']
    return frame


def tryLower():
    cities = ['Chicago', 'New York', 'Portland', 'San Francisco',
     'Austin', 'Boston']
    dfCities = pd.DataFrame(cities, columns=['Text'])
    frame = textLower(dfCities)

    for index, row in frame.iterrows():
        print(row['Text'])
#########################  main () #########################    
def main():
    tryLower()
like image 816
Bonson Avatar asked Sep 14 '25 05:09

Bonson


1 Answers

Try this:

dfCities["Text"].str.lower()

or this:

def textLower(x):
    return x.lower()

dfCities = dfCities["Text"].apply(textLower)
dfCities

#    0          chicago
#    1         new york
#    2         portland
#    3    san francisco
#    4           austin
#    5           boston
#    Name: Text, dtype: object
like image 172
Merlin Avatar answered Sep 15 '25 17:09

Merlin