You can use the pandas apply method to multiply random elements in your dataframe. Here's an example:
First, import pandas and numpy:
import pandas as pd
import numpy as np
Create a sample dataframe:
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
Use the apply method to multiply random elements in the dataframe:
df.apply(lambda x: x * np.random.randint(1, 5) if np.random.random() < 0.5 else x)
The above code multiplies random elements in the dataframe by a random integer between 1 and 4 if a random number between 0 and 1 is less than 0.5. Otherwise, it leaves the element unchanged.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-01-15 11:00:00 +0000
Seen: 10 times
Last updated: Jul 24 '22
How can you display a Pandas Dataframe using a for loop?
What changes need to be made to this for loop to be suitable for use with Pandas, Modin, or Ray?
What does it mean when my time-series code (pandas) shows a ValueError for freq T?
How to calculate the average value of a row in a pandas dataframe that contains NaN and arrays?
How can a single-column be made from a pandas data frame that has n columns?
What steps do I need to take to present a pandas DataFrame on a Django template?
How can I create a pandas dataframe using several OR operators in the statement?
How can the date format of dd/mm/yyyy be set in Pandas?
What is the method for producing a stacked n-series plot using Pandas and Matplotlib?