Pandas应用语法

2024-09-29 06:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何将一个简单的函数应用到Panda数据框中的每一行。在

示例:

def delLastThree(x):
    x = x.strip()
    x = x[:-3]
    return x

arr = ['test123','test234','test453']
arrDF = pandas.DataFrame(arr)
arrDF.columns = ['colOne']
arrDF['colOne'].apply(delLastThree)
print arrDF

我希望下面的代码对每一行都返回'test'。相反,它会打印原始值。在

如何将delLastThree函数应用于DF中的每一行?在


Tags: 数据函数示例pandasreturndefpandastrip
2条回答

当选择使用带df['colOne']的单括号时,您正在创建pd.Series。在

DataFrame上使用.apply(func, axis=1),即使用[['colOne']]进行选择,或者不选择任何列。然而,如果你需要修改cd6},那么你需要使用cd6}。在

对于使用['colOne']选择得到的pd.Series,您可以使用.apply()或{}。在

def delLastThree_series(x):
    x = x.strip()
    x = x[:-3]
    return x

def delLastThree_df(x):
    x = x.str.strip()
    x = x.str[:-3]
    return x

arr = ['test123','test234','test453']
arrDF = pd.DataFrame(arr)

arrDF.columns = ['colOne']

现在使用任意一个

^{pr2}$

或者

arrDF['colOne'].apply(delLastThree_series)
arrDF['colOne'].map(delLastThree_series, axis=1)

获得:

  colOne
0   test
1   test
2   test

当然,你也可以:

arrDF['colOne'].str.strip().str[:-3]

对序列使用map()函数(单列):

In [15]: arrDF['colOne'].map(delLastThree)
Out[15]:
0    test
1    test
2    test
Name: colOne, dtype: object

或者如果你想改变它:

^{pr2}$

但正如@Stefan所说,这将是更快、更高效、更“泛文化”的:

arrDF['colOne'] = arrDF['colOne'].str.strip().str[:-3]

或者,如果要删除所有尾随空格和数字:

arrDF['colOne'] = arrDF['colOne'].str.replace(r'[\s\d]+$', '')

测试:

In [21]: arrDF['colOne'].str.replace(r'[\s\d]+$', '')
Out[21]:
0    test
1    test
2    test
Name: colOne, dtype: object

相关问题 更多 >