Python 如何正确地迭代一组数据帧的每一行

Python 如何正确地迭代一组数据帧的每一行,python,pandas,dataframe,Python,Pandas,Dataframe,我正在尝试将strip()函数应用于一组pandas数据帧的所有行, 我正试图找出如何将这组数据帧转换为一个类,然后应用strip()函数,因为下一个错误是: AttributeError: 'DataFrame' object has no attribute 'strip' 下面是我对每一行的迭代尝试: for df in (df1, df2): df1 = df1.strip() df2 = df2.strip() 数据 有什么方法可以完成此任务吗?尝试(不使用f

我正在尝试将
strip()
函数应用于一组
pandas
数据帧的所有行, 我正试图找出如何将这组数据帧转换为一个类,然后应用
strip()
函数,因为下一个错误是:

AttributeError: 'DataFrame' object has no attribute 'strip'
下面是我对每一行的迭代尝试:

for df in (df1, df2):
    df1 = df1.strip()
    df2 = df2.strip()   
数据 有什么方法可以完成此任务吗?

尝试(不使用for循环):

或者说少一点冗长:

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

df1.apply(strip)
df2.apply(strip)
或用
替换

trailings = ['^\s+', '\s+$']
df1.replace(trailings, '', regex=True)
df2.replace(trailings, '', regex=True)
如果要使用循环,则更新数据帧的数据,而不是重新分配它们:

list_df = [df1, df2]
for df in [df1,df2]:
    # df = df.apply(strip) wouldn't work
    df[:] = df.apply(strip)
trailings = ['^\s+', '\s+$']
df1.replace(trailings, '', regex=True)
df2.replace(trailings, '', regex=True)
list_df = [df1, df2]
for df in [df1,df2]:
    # df = df.apply(strip) wouldn't work
    df[:] = df.apply(strip)