Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.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 迭代数据帧中的行,以在jupyter中查找索引、列中的值,并在csvfile中打印报告_Python_Pandas_Csv - Fatal编程技术网

Python 迭代数据帧中的行,以在jupyter中查找索引、列中的值,并在csvfile中打印报告

Python 迭代数据帧中的行,以在jupyter中查找索引、列中的值,并在csvfile中打印报告,python,pandas,csv,Python,Pandas,Csv,我想检查“权重”列中是否有小于90的值。如果是,我想将索引和值存储在一个变量中,这样我就可以在csvfile中打印出来。我使用了以下代码,但输出错误。请帮助 import csv import pandas as pd for index, row in df.iterrows(): if row['Weight'] < 90: result = index, row['Weight'] res = [result] csvfile = "<Report&g

我想检查“权重”列中是否有小于90的值。如果是,我想将索引和值存储在一个变量中,这样我就可以在csvfile中打印出来。我使用了以下代码,但输出错误。请帮助

import csv
import pandas as pd

for index, row in df.iterrows():
    if row['Weight'] < 90:
       result = index, row['Weight']

res = [result]
csvfile = "<Report>"

with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n''\n')
    for val in res:
        writer.writerow([val])  
导入csv
作为pd进口熊猫
对于索引,df.iterrows()中的行:
如果行['Weight']<90:
结果=索引,行['Weight']
res=[结果]
csvfile=“”
以open(csvfile,“w”)作为输出:
writer=csv.writer(输出,行终止符='\n'\n')
对于以res表示的val:
writer.writerow([val])

使用内置函数可以更简洁地完成此操作。比如:

output = df[df['Weight'] < 90]
output.to_csv(csvfile)
output=df[df['Weight']<90]
输出到_csv(csvfile)

有关将数据帧写入CSV的更多选项,请参阅。

省去for循环(这应该是您在
pandas
中的最后一个选择),而是:

df.loc[df.Weight < 90, 'Weight'].to_csv(csvfile)

或者更简单地说,不要在结果上循环使用
。writerows

with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='')
    writer.writerows(result) 

最后,对于
csv.writer
,您应该始终使用
lineterminator=''

不要迭代,使用基于
loc
的选择和矢量化布尔操作。我非常感谢您的帮助!代码工作完美无瑕!
writer.writerow([val])
writer.writerow(val)
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='')
    writer.writerows(result)