简体   繁体   English

如何遍历 CSV 文件并根据另一列的值更新一列中的值

[英]How to iterate over a CSV file and update values in one column based on the value of another column

I have a csv file with one column titled 'pages' that is empty for all of the rows of the file.我有一个 csv 文件,其中有一列标题为“页面”,对于文件的所有行都是空的。 I want to fill in this empty value in each row based on the value of 'size' for that row.我想根据该行的“大小”值在每一行中填写这个空值。 For example, if the size is less than 100, then I want the empty value to be replaced with 1, and if the 'size' value is greater than 100, I want the empty value to be replaced with 2. I am doing this in python.例如,如果 size 小于 100,那么我希望将空值替换为 1,如果 'size' 值大于 100,我希望将空值替换为 2。我正在这样做在 python 中。 I have tried some things like:我尝试了一些类似的东西:

data = pd.read_csv("example.csv")         
data["pages"] = ""      
data.to_csv("example.csv", index=False)
for row in data.iterrows(): 
    if row['size']>100:
        data["pages"]= "1" 

but it is not working.但它不工作。 I have uploaded an image of what the data may look like.我已经上传了数据可能是什么样子的图像。 在此处输入图像描述 Thank you for your help!谢谢您的帮助!

You can use apply method to do it.Try this你可以使用apply方法来做。试试这个

data["pages"] = data["size"].apply(lambda x: "2" if x>100 else "1")

Or like this或者像这样

data["pages"] = (data["size"]>100).map({True: '2', False: '1'})

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

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