就地应用于满足条件的 pandas 数据框的列 [英] inplace apply to columns of pandas dataframe satisfying conditions
本文介绍了就地应用于满足条件的 pandas 数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下熊猫数据框:
Consider the following pandas dataframe:
df = pd.DataFrame({'t': [1,2,3], 'x1': [4,5,6], 'x2': [7,8,9]} )
>>> print(df)
t x1 x2
0 1 4 7
1 2 5 8
2 3 6 9
我想对那些名称包含字符'x'的列应用一个函数(例如乘以2)
I would like to apply a function (say multiplying by 2) to those columns with names containing the character 'x'
这可以通过以下方式完成:
This can be done by:
df.filter(regex='x').apply(lambda c: 2*c)
,但未安装到位.我的解决方案是:
but not in place. My solution is:
tmp = df.filter(regex='x')
tmp = tmp.apply(lambda c: 2*c)
tmp['t'] = df['t']
df = tmp
具有更改列顺序的附加问题.有没有更好的办法?
which has the added problem of changing the order of the columns. Is there a better way?
推荐答案
IIUC,您可以执行以下操作:
IIUC you can do something like this:
In [239]: df.apply(lambda x: x*2 if 'x' in x.name else x)
Out[239]:
t x1 x2
0 1 8 14
1 2 10 16
2 3 12 18
更新:
In [258]: df.apply(lambda x: x*2 if 'x' in x.name else x) \
.rename(columns=lambda x: 'ytext_{}_moretext'.format(x[-1]) if 'x' in x else x)
Out[258]:
t ytext_1_moretext ytext_2_moretext
0 1 8 14
1 2 10 16
2 3 12 18
这篇关于就地应用于满足条件的 pandas 数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文