Python 将列除以值

Python 将列除以值,python,pandas,Python,Pandas,我有一个csv文件,它有29列,如下所示: 还有,我有一个文件夹,里面有一堆图片 此csv包含images文件夹中每个图像的标题和地面真实点。它有29列。第一列是文件名,接下来的28列是14个面点的x和y坐标 我的代码: def load_imgs_and_keypoints(dirname='facial-keypoints', image_size=(100, 100)): images = [] points = [] base_path = '/content/facial

我有一个csv文件,它有29列,如下所示:

还有,我有一个文件夹,里面有一堆图片

此csv包含images文件夹中每个图像的标题和地面真实点。它有29列。第一列是文件名,接下来的28列是14个面点的x和y坐标

我的代码:

def load_imgs_and_keypoints(dirname='facial-keypoints', image_size=(100, 100)):

  images = []
  points = []
  base_path = '/content/facial-keypoints/data/images'

  # Get all the images
  for file in os.listdir(base_path):

    # Set the path and read the image
    full_img_path = os.path.join(base_path, file)
    image = cv2.imread(full_img_path)

    # Get the rows and cols of image
    rows = image.shape[0]
    cols = image.shape[1]
    channels = image.shape[2]

    rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    rgb_image = cv2.resize(rgb_image, image_size)
    images.append(rgb_image)

  # Read the csv file which contains facial keypoints
  csv_path = '/content/facial-keypoints/data/gt.csv'
  csv_file = pd.read_csv(csv_path)
  print(csv_file.head())

  print('------------------------------------------------------------------------')

  # Scale the coordinates
  all_X_cols = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 
                'x11', 'x12', 'x13','x14']

  all_Y_cols = ['y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'y7', 'y8', 'y9', 'y10', 
                'y11', 'y12', 'y13','y14']
我想做的是-

将所有x除以图像列的列数,将所有y除以图像行的行数,然后从所有值中减去0.5

我不知道如何从csv中获取所有的X和Y,并执行必要的操作

我怎样才能完成这项任务


谢谢。

答案相对简单。本质上,您只需循环遍历列,并将所需的操作应用于每一列。要执行该操作,不需要任何特殊功能。你可以把它写成一个向量化的运算,把你的级数当作一个向量,可以用一个标量来除/减。如果要包含文件名列,可以更改列的计数方式

all_X_cols = [i for i in csv_file.columns if "x" in i]
all_Y_cols = [i for i in csv_file.columns if "y" in i]

num_cols = len([i for i in csv_file.columns if i != "filename"])
num_rows = len(sv_file)

for x in all_X_cols:
    csv_file[x] = (csv_file[x]/num_cols)-.5

for y in all_Y_cols:
    csv_file[y] = (csv_file[y]/num_rows)-.5

尝试另一种方法:

for col in df.columns:
    if (col[0]=='x'):
        df[col] = np.where(df['filename'] == file, df[col] / cols, df[col])
    else:
        df[col] = np.where(df['filename'] == file, df[col] / rows, df[col])

这很简单。但是列出所有的栏目不是很乏味吗?我只是想知道是否有一个解决方案,我不必列出列。我编辑了这个解决方案以包括您的问题。如果您可以保证列的命名一致,那么我在这里使用和展示的方法是有效的。在本例中,我们知道可以根据名称中是否有“x”或“y”来分隔列。现在您不必复制/粘贴,并且可以在不需要更改代码的情况下添加x/y列。抱歉,我想我一开始误解了您的问题。我以为你是在问如何获取操作的实际X和Y列,而不是如何获取这些列的标签。不用担心,这个解决方案非常有效。非常感谢。对您需要用数据帧的名称替换df