我有一个包含多个字符串列的数据框。我想使用对数据帧的多列上的系列有效的字符串方法。我希望这样的事情:
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 对象有效。执行此操作最合适/最pandas-y的方法是什么?
功能rstrip http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.rstrip.html与...一起工作Series
所以可以使用apply http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html:
df = df.apply(lambda x: x.str.rstrip('f'))
或者创建Series
by stack http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html最后unstack http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html:
df = df.stack().str.rstrip('f').unstack()
Or use applymap http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html:
df = df.applymap(lambda x: x.rstrip('f'))
最后,如果需要将函数应用于某些列:
#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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)