Home > Mobile >  How to parametrize a column index in pandas?
How to parametrize a column index in pandas?

Time:11-16

Sometimes I want to use all columns and sometimes I want to exclude the last column.

df.iloc[:, :].apply(foobar)  # all columns
df.iloc[:, :-1].apply(foobar)  # exclude last column

Can I parameterize that somehow?

if exclude_last:
   idx = ':-1'
else:
   idx = ':'

df.iloc[:, idx].apply(foobar)

CodePudding user response:

You can use a ternary construct:

df.iloc[:, :-1 if exclude_last else df.shape[1]].apply(foobar)

Example:

df = pd.DataFrame(columns=list('ABCD'), index=[0])

#      A    B    C    D
# 0  NaN  NaN  NaN  NaN


exclude_last = True
df.iloc[:, :-1 if exclude_last else df.shape[1]]

#      A    B    C
# 0  NaN  NaN  NaN

exclude_last = False
df.iloc[:, :-1 if exclude_last else df.shape[1]]

#      A    B    C    D
# 0  NaN  NaN  NaN  NaN

hacky alternative

A hacky alternative (but less readable, don't use it in production code):

df.iloc[:, :df.shape[1]-exclude_last]

CodePudding user response:

You can use df.columns for this purpose:

if exclude_last:
   cols = df.columns[:-1]
else:
   cols = df.columns

df.loc[:, cols].apply(foobar)
  • Related