简体   繁体   English

将函数应用于pandas数据框中的所有其他列

[英]Applying function to every other column in pandas dataframe

I have the below code which rounds every column in my dataframe: 我有以下代码将数据框中的每一列四舍五入:

def column_round(decimals):
    return partial(pd.Series.round, decimals=decimals)

df = df.apply(column_round(2))

I'd like to do this to every other column, in a new dataframe that I have. 我想对我拥有的新数据框中的所有其他列执行此操作。 I believe i read somewhere that :: is a built in notation for stepping, but i'm not quite sure how to use it. 我相信我在某处读到::是步进的内置符号,但是我不太确定如何使用它。

You can do: 你可以做:

df[df.columns[::2]].apply(column_round(2))

This steps over the df columns so you can sub-select them 这将遍历df列,因此您可以对其进行子选择

Example: 例:

In [2]:
df = pd.DataFrame(columns=list('abcdefgh'))
df

Out[2]:
Empty DataFrame
Columns: [a, b, c, d, e, f, g, h]
Index: []

In [3]:
df.columns[::2]

Out[3]:
Index(['a', 'c', 'e', 'g'], dtype='object')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM