【发布时间】:2018-11-16 09:13:07
【问题描述】:
我正在尝试创建一些代码,它将对特定数据库列的每一行应用一个函数。我见过的其他帖子似乎在所有列的行上应用了一个函数,这不是我需要的。
我试图做的是对数据进行子集化以获取仅包含我需要的列的数据库(下面脚本中的“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__
)
【问题讨论】:
-
您能提供一些输入数据和预期的输出吗?
-
如果你在列上使用 for 循环,你通常会做错事
-
我之前尝试使用 with 语句,但得到了一个失败的 exit 语句。堆栈成员告诉我应该尝试其他方法。我将编辑并添加有关目的的更多详细信息。
-
您是否尝试将
apply函数添加到列数据?还是直接打印出来?如果打印,请查看标记的重复项
标签: python python-3.x pandas csv