Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.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
Python Pandas:以其名称满足条件为条件的相乘列_Python_Pandas - Fatal编程技术网

Python Pandas:以其名称满足条件为条件的相乘列

Python Pandas:以其名称满足条件为条件的相乘列,python,pandas,Python,Pandas,我在Python中使用熊猫。我正在处理的数据帧示例如下: pd.DataFrame({"A1": [1,2,3], "A2": [1,2,3], "A3": [1,2,3], "A4": [1,2,3], "B1": [3,2,1], "B2": [3,2,1], "B3": [3,2,1], "B4": [3,2,1]}) 如果列名以4结尾,我想将该列乘以10。因此,在这种情况下,期望的输出是 pd.DataFrame({"A1": [1,2,3], "A2": [1,2,3], "A3":

我在Python中使用熊猫。我正在处理的数据帧示例如下:

pd.DataFrame({"A1": [1,2,3], "A2": [1,2,3], "A3": [1,2,3], "A4": [1,2,3], "B1": [3,2,1], "B2": [3,2,1], "B3": [3,2,1], "B4": [3,2,1]})
如果列名以4结尾,我想将该列乘以10。因此,在这种情况下,期望的输出是

pd.DataFrame({"A1": [1,2,3], "A2": [1,2,3], "A3": [1,2,3], "A4": [10,20,30], "B1": [3,2,1], "B2": [3,2,1], "B3": [3,2,1], "B4": [30,20,10]})
请注意,仅更改了列A4和B4


如何执行此操作?

使用
columns.str.endswith
iloc
选择列,然后乘以值ie

cols = df.columns.str.endswith('4')
df.iloc[:,cols] =  df.iloc[:,cols]*10
输出:

A1 A2 A3 A4 B1 B2 B3 B4 0 1 1 1 10 3 3 3 30 1 2 2 2 20 2 2 2 20 2 3 3 3 30 1 1 1 10 A1 A2 A3 A4 B1 B2 B3 B4 0 1 1 1 10 3 3 3 30 1 2 2 2 20 2 2 2 20 2 3 3 3 30 1 1 1 10
我们还可以进行速记赋值,即使用
columns.str.endswith
iloc
选择列,然后乘以值ie

cols = df.columns.str.endswith('4')
df.iloc[:,cols] =  df.iloc[:,cols]*10
输出:

A1 A2 A3 A4 B1 B2 B3 B4 0 1 1 1 10 3 3 3 30 1 2 2 2 20 2 2 2 20 2 3 3 3 30 1 1 1 10 A1 A2 A3 A4 B1 B2 B3 B4 0 1 1 1 10 3 3 3 30 1 2 2 2 20 2 2 2 20 2 3 3 3 30 1 1 1 10
我们还可以进行速记赋值,即选择要与数组相乘的列,即df.iloc[:,cols]*=10

import pandas as pd

df = pd.DataFrame({"A1": [1,2,3], "A2": [1,2,3], "A3": [1,2,3], "A4": [1,2,3], "B1": [3,2,1], "B2": [3,2,1], "B3": [3,2,1], "B4": [3,2,1]})

cols = [i for i in df.columns if i.endswith("4")]
df[cols] *= 10

df
输出:

    A1  A2  A3  A4  B1  B2  B3  B4
0   1   1   1   10  3   3   3   30
1   2   2   2   20  2   2   2   20
2   3   3   3   30  1   1   1   10
与iloc相比,我的设置有一些小的时间改进:

  • 100圈,最佳3圈:每圈2.45毫秒
  • 100个回路,最佳3个:每个回路2.04 ms(Bharaths溶液)

  • 选择要与数组相乘的列的替代解决方案

    import pandas as pd
    
    df = pd.DataFrame({"A1": [1,2,3], "A2": [1,2,3], "A3": [1,2,3], "A4": [1,2,3], "B1": [3,2,1], "B2": [3,2,1], "B3": [3,2,1], "B4": [3,2,1]})
    
    cols = [i for i in df.columns if i.endswith("4")]
    df[cols] *= 10
    
    df
    
    输出:

        A1  A2  A3  A4  B1  B2  B3  B4
    0   1   1   1   10  3   3   3   30
    1   2   2   2   20  2   2   2   20
    2   3   3   3   30  1   1   1   10
    
    与iloc相比,我的设置有一些小的时间改进:

  • 100圈,最佳3圈:每圈2.45毫秒
  • 100个回路,最佳3个:每个回路2.04 ms(Bharaths溶液)

  • 让我们这样做
    df.iloc[:,cols]*=10
    让我们这样做
    df.iloc[:,cols]*=10