Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

python - How to properly iterate over each row for a set of pandas dataframe

I am trying to apply strip() function to all rows for a set of pandas dataframes, I am trying to figure out how to convert this set of dataframes into a class and then apply a strip() function, as the error is the next one:

AttributeError: 'DataFrame' object has no attribute 'strip'

Here's my attempt to iterate over each row:

for df in (df1, df2):
    df1 = df1.strip()
    df2 = df2.strip()   

data

import pandas as pd

df1= pd.DataFrame(data={'col1': [' hey ' , ' world ', "-"], 'col2': [' hello ' , "-", ' world ']})
df2 = pd.DataFrame(data={'col3': [' brazil ' , ' china ', "-"], 'col4': [' russia ' , "-", ' india ']})

Is there any way to accomplish this task?

question from:https://stackoverflow.com/questions/65908656/how-to-properly-iterate-over-each-row-for-a-set-of-pandas-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try (without the for loop):

df1 = df1.apply(lambda x: x.str.strip())
df2 = df2.apply(lambda x: x.str.strip())

Or a bit less verbose:

strip = lambda s: s.str.strip()

df1.apply(strip)
df2.apply(strip)

Or with replace:

trailings = ['^s+', 's+$']
df1.replace(trailings, '', regex=True)
df2.replace(trailings, '', regex=True)

If you want to use loop, then update the data of the dataframe, instead of reassigning them:

list_df = [df1, df2]
for df in [df1,df2]:
    # df = df.apply(strip) wouldn't work
    df[:] = df.apply(strip)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...