如何在python中检查不同csv文件的两列?

时间:2019-01-21 07:53:50

标签: python

row [1]和i [0]具有两个不同的csv文件的影片ID。如何比较不同文件的影片ID?

import csv
total=0
k=0
with open('R\genre_matrix2.csv')as Genre:
        csv_genre=csv.reader(Genre,delimiter=',')  

        with open('ratings1234.csv') as CsvFile:
            csv_rating=csv.reader(CsvFile,delimiter=',')
            for xy in range(1,611):
                for row in csv_rating:
                    if row[0] == xy:
                        i=float(row[2])
                        j=float(row[4])
                        k=i*j

                    for i in csv_genre: 

                        if(row[1] == i[0]):

                            val =  [x * k for x in i]
                            total+=val
                            print(row[0] + "\t" + total)

1 个答案:

答案 0 :(得分:1)

早上好!

您是否考虑过使用熊猫和pandas.read_csv功能?

代码如下所示

import pandas as pd

df = pd.read_csv('R\genre_matrix2.csv', delimiter=',')
df_2 = pd.read_csv('ratings1234.csv')

# looping through the files
# the following code is just a simple example
for i in range(1, df.shape[0]):
    # select row of first dataframe
    df_row = df.iloc[i, columns_index] 
    # select row of second dataframe
    df_row_2 = df_2.iloc[i, columns_index] 
    # compare
    df_row == df_row_2

这可能会简化您的代码。