1

DataFrame

A B C
1 2 3
2 4 6

array = [1,10,100]

Result:

A   B   C
1   2   3
2   4   6
10  20  30
20  40  60
100 200 300
200 400 600

Array and dataframe length can be of any size, not necessarily the same.

I have done using FOR loop which is too slow if I have large dataframe or too many of them.

Below is my sample snippet:

for i in array:
    pr[pr.select_dtypes(include=['number']).columns] *= i
    fdf = np.concat([fdf,pr],axis=0)

Is there a much faster way to do this. I am dealing with multiple dataframes which after this operation needs to concatenated.

4 Answers 4

3
mult = df.values * np.array([1,10,100])[:, np.newaxis, np.newaxis]
pd.DataFrame(mult.reshape((-1, 3)), columns=df.columns)

     A    B    C
0    1    2    3
1    2    4    6
2   10   20   30
3   20   40   60
4  100  200  300
5  200  400  600
Sign up to request clarification or add additional context in comments.

Comments

2

Use pandas.concat

pd.concat([df * n for n in a], ignore_index=True)

     A    B    C
0    1    2    3
1    2    4    6
2   10   20   30
3   20   40   60
4  100  200  300
5  200  400  600

Setup

io_ = pd.io.common.StringIO

def rpd(text='', sep='\s{1,}', *args, **kwargs):
  kw = dict(engine='python', sep=sep)
  return pd.read_csv(io_(text), *args, **kw, **kwargs)

df = rpd("""\
A B C
1 2 3
2 4 6""")

a = np.array([1, 10, 100])

2 Comments

ignore_index=True ?
Yes (-: was getting there
2

IIUC

pd.DataFrame(np.vstack([df.values*x for x in ary]))
Out[171]: 
     0    1    2
0    1    2    3
1    2    4    6
2   10   20   30
3   20   40   60
4  100  200  300
5  200  400  600

pandas reindex

df.reindex(df.index.tolist()*(len(ary))).reset_index(drop=True).mul(pd.Series(np.repeat(ary,len(df))),0)
Out[201]: 
     A    B    C
0    1    2    3
1    2    4    6
2   10   20   30
3   20   40   60
4  100  200  300
5  200  400  600

Comments

0
df = pd.DataFrame({'A':[1,2],'B':[2,4],'C':[3,6]})
ar = [1,10,100]

result = pd.concat([df * i for i in ar], ignore_index = True)

1 Comment

This is exactly my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.