Ask Your Question
0

How can I multiply random elements in my dataframe?

asked 2022-01-15 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-07-24 20:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-01-15 11:00:00 +0000

Seen: 10 times

Last updated: Jul 24 '22