I have the following dataframe:
# List of Tuples
matrix = [([22, 23], [34, 35, 65], [23, 29, 31]),
([33, 34], [31, 44], [11, 16, 18]),
([44, 56, 76], [16, 34, 76], [21, 34]),
([55, 34], [32, 35, 38], [22, 24, 26]),
([66, 65, 67], [33, 38, 39], [27, 32, 34]),
([77, 39, 45], [35, 36, 38], [11, 21, 34])]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'), index=list('abcdef'))
I'm able to apply my custom function to output start, end items in list like below for all columns:
def fl(x):
return [x[0], x[len(x)-1]]
df.apply(lambda x : [fl(i) for i in x])
But i want to apply the function to selected columns x & z.
I'm trying like below referring to this link
df.apply(lambda x: fl(x) if x in ['x', 'y'] else x)
and like this:
df[['x', 'y']].apply(fl)
How to get the output with the function applied to only x and z columns with y column unchanged.