![](/img/trans.png)
[英]Using python, I need to average value based on two keys in two columns from a CSV file
[英]Comparing two columns in a csv file using python based on value in third column
我在csv文件中有三列
Number Value Checked
1111 5
1234 6
1111 0 yes
4444 0 yes
5555 8
4444 7
如果选中的字段为“是”,我需要查找是否在“编号”列中重复了与之关联的编号。 如果是,那么我希望“已检查”字段显示“是”
输出示例:
Number Value Checked
1111 5 yes
1234 6
1111 0 yes
4444 0 yes
5555 8
4444 7 yes
我正在使用python。 这是一个csv文件。 抱歉,我是Stackoverflow的新手。 基本上,我试图读取列中的值总计为0的行。如果它们为0,则创建了一个“ Checked”列,对变为null的值说“是”。 例如,如果数字“ 111111”具有值“ -8”和“ 8”,则在执行sumif后,它将表示为0,因此选中的字段将为“是”。 但是问题是我的代码读取的是另一行,因此,如果有两行的值分别为“ 9”和“ -9”,则仅第二行而不是第一行得到0。 我希望选中的列为这两行都添加“是”。 这是我的代码的一部分:
edict={}
if edict.get(newrow[-10],"")=="":
edict[newrow[-10]]=newrow[47]
else:
edict[newrow[-10]]=float(newrow[47])+float(edict[newrow[-10]])
newrow[-9]=edict[newrow[-10]]
if newrow[-9]==0:
newrow[-11]="Hide"
第10列是字段编号,第47列是值,第11列已选中
让我知道是否不清楚。
算法:
csv
模块读取输入的CSV文件。 info
以保存行详细信息,并创建checked_value
以获得选中的yes数字。 info
添加行 yes
,如果是,则在checked_value
列表中追加row[0]
号。 info
字典,并再次检查每一行,如果row[0]
数checked_value
列表或没有,如果存在更新行yes
。 -
码:
import csv
import pprint
input_file = "input1.csv"
with open(input_file, 'rb') as fp:
root = csv.reader(fp)
info = {}
checked_value = []
for i, row in enumerate(root):
info[i] = row
if row[2]=="yes":
checked_value.append(row[0])
print "Debug 1: info: "
pprint.pprint(info)
for i,j in info.items():
if j[0] in checked_value:
j[2] = "yes"
print "Debug 2: info: "
pprint.pprint(info)
#- Write file
with open("output1.csv", 'wb') as fp:
root = csv.writer(fp, delimiter=',')
root.writerows(info.values())
输出:调试语句:
vivek@vivek:~/Desktop/stackoverflow/anna$ python 6.py
Debug 1: info:
{0: ['Number', 'Value', 'Checked'],
1: ['1111', '5', ''],
2: ['1234', '6', ''],
3: ['1111', '0', 'yes'],
4: ['4444', '0', 'yes'],
5: ['5555', '8', ''],
6: ['4444', '7', '']}
Debug 2: info:
{0: ['Number', 'Value', 'Checked'],
1: ['1111', '5', 'yes'],
2: ['1234', '6', ''],
3: ['1111', '0', 'yes'],
4: ['4444', '0', 'yes'],
5: ['5555', '8', ''],
6: ['4444', '7', 'yes']}
Output1.csv
Number,Value,Checked
1111,5,yes
1234,6,
1111,0,yes
4444,0,yes
5555,8,
4444,7,yes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.