Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 有没有办法通过将现有数据帧的一列与其余列相乘来快速创建新数据帧_Pandas_Dataframe - Fatal编程技术网

Pandas 有没有办法通过将现有数据帧的一列与其余列相乘来快速创建新数据帧

Pandas 有没有办法通过将现有数据帧的一列与其余列相乘来快速创建新数据帧,pandas,dataframe,Pandas,Dataframe,我有以下dataframe(假设我有更多的列): 我想将列m乘以列a和b元素,并返回以下数据帧: a b t1 1 2 t2 2 4 t3 3 6 目前,我首先将列m转换为向量。想知道是否有人有更直接的方法?我想你需要: 如果只需要m的多个a和b列: print (df[['a','b']].mul(df.m, axis=0)) a b t1 1 2 t2 2 4 t3 3 6 如果列m为第一列,则可以选择所有列,而不选择“第一个由”,然后选择多个: print

我有以下dataframe(假设我有更多的列):

我想将列
m
乘以列
a
b
元素,并返回以下数据帧:

   a b
t1 1 2
t2 2 4
t3 3 6
目前,我首先将列
m
转换为向量。想知道是否有人有更直接的方法?

我想你需要:

如果只需要
m
的多个
a
b
列:

print (df[['a','b']].mul(df.m, axis=0))
    a  b
t1  1  2
t2  2  4
t3  3  6
如果列
m
为第一列,则可以选择所有列,而不选择“第一个由”,然后选择多个:

print (df.iloc[:, 1:])
    a  b
t1  1  2
t2  1  2
t3  1  2

df = df.iloc[:, 1:].mul(df.m, axis=0)
print (df)
    a  b
t1  1  2
t2  2  4
t3  3  6
更普遍的是,过滤列不是列表理解的
m

cols = [col for col in df.columns if col !='m']
print (cols)
['a', 'b']

df = df[cols].mul(df.m, axis=0)
print (df)
    a  b
t1  1  2
t2  2  4
t3  3  6
计时

#[300000 rows x 2 columns]
df = pd.concat([df]*100000).reset_index(drop=True)

In [438]: %timeit (df[['a','b']].mul(df.m, axis=0))
100 loops, best of 3: 5.41 ms per loop

In [439]: %timeit (df.iloc[:, 1:].mul(df.m, axis=0))
100 loops, best of 3: 2.66 ms per loop

In [440]: %timeit (df[['a','b']].apply(lambda x: x*df.m))
100 loops, best of 3: 10.3 ms per loop
我认为你需要:

如果只需要
m
的多个
a
b
列:

print (df[['a','b']].mul(df.m, axis=0))
    a  b
t1  1  2
t2  2  4
t3  3  6
如果列
m
为第一列,则可以选择所有列,而不选择“第一个由”,然后选择多个:

print (df.iloc[:, 1:])
    a  b
t1  1  2
t2  1  2
t3  1  2

df = df.iloc[:, 1:].mul(df.m, axis=0)
print (df)
    a  b
t1  1  2
t2  2  4
t3  3  6
更普遍的是,过滤列不是列表理解的
m

cols = [col for col in df.columns if col !='m']
print (cols)
['a', 'b']

df = df[cols].mul(df.m, axis=0)
print (df)
    a  b
t1  1  2
t2  2  4
t3  3  6
计时

#[300000 rows x 2 columns]
df = pd.concat([df]*100000).reset_index(drop=True)

In [438]: %timeit (df[['a','b']].mul(df.m, axis=0))
100 loops, best of 3: 5.41 ms per loop

In [439]: %timeit (df.iloc[:, 1:].mul(df.m, axis=0))
100 loops, best of 3: 2.66 ms per loop

In [440]: %timeit (df[['a','b']].apply(lambda x: x*df.m))
100 loops, best of 3: 10.3 ms per loop

类似地,也许更容易看到如何推广到其他操作,
df[['a','b']].apply(lambda x:x*df.m)
Ya,但apply非常慢。@vmg-I添加计时,速度较慢,但测试只在两列中进行。类似地,也许更容易看到如何推广到其他操作,
df['a','b'].apply(lambda x:x*df.m)
Ya,但apply非常慢。@vmg-I添加计时,速度比较慢,但测试只在两列中进行。