繁体   English   中英

检查 csv 文件中的列中是否存在值 (Python)

[英]Check if value exists in a column in a csv file (Python)

我有一个 csv 文件,希望能够检查列中是否存在值。 例如:

Frame,LED,R,G,B,W
2,8,0,0,0,126
3,1,0,0,0,126
17,1,0,0,0,126
19,1,0,0,0,126
20,1,0,0,0,126

我需要一条线来表明“17”已经存在于“框架”列中

这应该很容易,并且已经有关于如何实现这一点的帖子和文章,但我现在已经尝试了很多东西,这让我觉得我之前犯了一个错误,导致“搜索”功能无法正常工作。

import os
import pandas as pd
import csv

# bin/cache/temp.csv
'''
Frame,LED,R,G,B,W
1,1,0,0,0,126
1,1,0,0,0,126
2,1,0,0,0,126
etc
'''

def this_is_the_code_used_to_add_column_names():
    if not os.path.exists('bin/cache/temp.csv'):
        with open('bin/cache/temp.csv', 'a', encoding='UTF8', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(['Frame', 'LED', 'R', 'G', 'B', 'W'])

def this_is_the_code_used_to_write_and_sort_the_data():
    with open('bin/cache/temp.csv', 'a', encoding='UTF8', newline='') as file:
            writer = csv.writer(file)
            writer.writerow('var_1', 'var_2', 'ver_3', 'ver_4', 'var_5', 'var_6')
        
    dataFrame = pd.read_csv('bin/cache/temp.csv')
    dataFrame.sort_values(["Frame","LED"],axis=0, ascending=True,inplace=True,na_position='first') # Sorting file
    dataFrame.to_csv('bin/cache/temp.csv', sep=',', encoding='utf-8', index=False) # Write to file new data

def the_part_that_is_not_working():
    df = pd.read_csv('bin/cache/temp.csv')
    # Need a line to return True or a list with all entries with the searched-for value
    # Just any metric that will indicate if it exists
    # Ideally with a way to reference back to it like an index, but I'll cross that bridge
    print(df[df['Frame']=='1'].index.tolist())

the_part_that_is_not_working()

上面的代码显示了我程序中与 csv 文件的每次交互,如果文件不存在,则在运行时创建它并添加标头。 然后可以用数据写入行,然后是整个文件的一种。 我的目标是添加一种方法来检查“框架”“17”是否已经存在,因此没有重复项。

我有过多的输出和错误,所以我没有包括我尝试过的所有解决方案,但基本上,名为the_part_that_is_not_working的 function 是我一直试图开始工作的。

任何帮助将不胜感激。

要检查Frame列中的值17是否存在,您可以使用.any()

df = pd.read_csv('your_data.csv')

out = df['Frame'].eq(17).any()
print(out)

印刷:

True

事实证明,问题是数据被读取为 int 而不是 str。

解决办法是改变这个:

x = df[df['Frame']=='1'].index.tolist()

进入这个...

x = df[df['Frame']==1].index.tolist()

这将返回一个列表,其中包含每次出现的索引

很高兴知道 csv 文件不专门返回字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM