Select a number of columns at a random state
In this approach, If the user wants to select a certain number of columns more than 1 we use the parameter ‘n’ for this purpose. In the below example, we give n as 5. randomly selecting 5 columns from the database.
Python3
# import packages import pandas as pd # reading csv file df = pd.read_csv( 'fossilfuels.csv' ) pd.set_option( 'display.max_columns' , None ) print (df.head()) print () # randomly selecting columns df = df.sample(n = 5 , axis = 'columns' ) print (df.head()) |
Output:
Randomly Select Columns from Pandas DataFrame
In this article, we will discuss how to randomly select columns from the Pandas Dataframe.
According to our requirement, we can randomly select columns from a pandas Database method where pandas df.sample() method helps us randomly select rows and columns.
Syntax of pandas sample() method:
Return a random selection of elements from an object’s axis. For repeatability, you may use the random_state parameter.
DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
Parameters:
- n: int value, Number of random rows to generate.
- frac: Float value, Returns (float value * length of data frame values ). frac cannot be used with n.
- replace: Boolean value, return sample with replacement if True.
- random_state: int value or numpy.random.RandomState, optional. if set to a particular integer, will return same rows as sample in every iteration.
- axis: 0 or ‘row’ for Rows and 1 or ‘column’ for Columns.
Contact Us