在特定文件列的每一行上应用一个for循环

时间:2018-11-16 09:13:08

标签: python python-3.x pandas csv

我正在尝试创建一些代码,以将功能应用于特定数据库列的每一行。我见过的其他帖子似乎在所有列的行上应用了一个函数,这不是我所需要的。

我试图做的是将数据子集化为仅包含我需要的列的数据库(以下脚本中的“ blargh”),然后尝试通过for循环搅动数据库。但是,我不确定如何遍历每一行。有人可以帮助我了解如何在for循环下面创建函数吗?

import pandas as pd
import os.path

# Get the path to the demos directory.
base_path = os.path.dirname(__file__)

text_file = pd.read_csv(os.path.join(base_path, "names.txt"), sep = ';    ' , engine='python')

# subsetting
blargh = text_file[["Name"]]
print(blargh)

# attempting to make a for loop
for row in blargh:
    print(row)

编辑:根据要求,这是我尝试执行此操作的背景。 This is an attempt to fix a problem I was investigating in an earlier post but I haven't made any worthwhile progress. Click here to see the original problem

基本上,我正在尝试使用pylabels包创建可打印的名称标签。原始代码使用txt文件,其中每一行都是一个名称。我希望在名称标签上添加更多详细信息,因此我试图修改代码以将其纳入数据库,并向每个标签添加适当的信息。原始脚本具有以下代码:

with open(os.path.join(base_path, "names.txt")) as names:
    sheet.add_labels(name.strip() for name in names)

其中sheet = labels.Sheet(specs, write_name, border=True)。当我尝试将其修改为:

with text_file[["Name"]] as names:
    sheet.add_labels(name.strip() for name in names)

我有一个AttributeError: __exit__。有人建议使用try / finally语句,但我似乎无法使其正常工作。

(完整错误:

Traceback (most recent call last):
  File "sticker.V.7.py", line 173, in <module>
    with text_file[["Name"]] as names:
AttributeError: __exit__

1 个答案:

答案 0 :(得分:0)

您需要将制作的数据框(即text_file [[“ Name”]])保存到文件中。所以:

data = text_file[["Name"]]
data.to_csv("data.csv", sep=",")

with语句仅适用于定义了 enter exit 函数的特殊对象。 DataFrame不是那个对象,但是open(“ file.csv”,“ r”)的结果具有此功能。

现在,您可以:

with open(os.path.join(base_path, "data.csv")) as names:
    sheet.add_labels(name.strip() for name in names)