如何将字符串方法应用于数据框的多个列 [英] How to apply string methods to multiple columns of a dataframe
本文介绍了如何将字符串方法应用于数据框的多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有多个字符串列的数据框.我想使用一个字符串方法,该方法对于数据框的多个列上的一系列有效.我希望这样的事情:
I have a dataframe with multiple string columns. I want to use a string method that is valid for a series on multiple columns of the dataframe. Something like this is what I would wish for:
df = pd.DataFrame({'A': ['123f', '456f'], 'B': ['789f', '901f']})
df
Out[15]:
A B
0 123f 789f
1 456f 901f
df = df.str.rstrip('f')
df
Out[16]:
A B
0 123 789
1 456 901
很显然,这是行不通的,因为str操作仅对pandas Series对象有效.什么是/最适合熊猫的方法?
Obviously, this doesn't work because str operations are only valid on pandas Series objects. What is the appropriate/most pandas-y method to do this?
推荐答案
函数 apply
:
Function rstrip
working with Series
so is possible use apply
:
df = df.apply(lambda x: x.str.rstrip('f'))
Or create Series
by stack
and last unstack
:
df = df.stack().str.rstrip('f').unstack()
或使用 applymap
:
df = df.applymap(lambda x: x.rstrip('f'))
最后一次需要将功能应用于某些列:
Last if need apply function to some columns:
#add columns to lists
cols = ['A']
df[cols] = df[cols].apply(lambda x: x.str.rstrip('f'))
df[cols] = df[cols].stack().str.rstrip('f').unstack()
df[cols] = df[cols].stack().str.rstrip('f').unstack()
这篇关于如何将字符串方法应用于数据框的多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文