Python 3.x Python:读取数据文件并处理/过滤数据
我最近开始学习Python,试图抓住概念,同时获得了一个30K行的示例数据文件,如下所示,用空格分隔Python 3.x Python:读取数据文件并处理/过滤数据,python-3.x,Python 3.x,我最近开始学习Python,试图抓住概念,同时获得了一个30K行的示例数据文件,如下所示,用空格分隔 P160543 East Asia and Pacific IN C P166720 Africa IN N P165276 East Asia and Pacific AD n IIST P159835 Latin America and Caribbean LA B P160778 Latin America and Caribbean LA B
P160543 East Asia and Pacific IN C
P166720 Africa IN N
P165276 East Asia and Pacific AD n IIST
P159835 Latin America and Caribbean LA B
P160778 Latin America and Caribbean LA B
P164290 South Asia AS N
P165493 South Asia SA N
P165585 Latin America and Caribbean LAC N
P157987 South Asia SA C ALAESH
P158364 South Asia SAS B EPATET
请给出建议。创建一个生成器以循环文件的行 从文件的第一行获取标题
def read_file(fullname):
with open(fullname) as f:
for line in f:
yield header_line, line
这应该足够让你开始了,因为这闻起来像是家庭作业
小心任何推荐pandas的人-我在大数据环境中工作,pandas不工作,而多gig文件/数百万记录生成器将工作。删除了列标题。。。刚刚意识到文件没有标题行fyi(其他人回答):header\u line=“id RegionName TypeSt TypePD TypeCode”谢谢Schalton。抱歉,我已从文件中删除标题行。。。刚刚意识到文件没有标题行来标识列名称。您可以从生成器中删除标题索引,并在循环外部设置标题字符串或列表。这应该足以让您继续。如果您正在寻找一个完全编码的解决方案,请跳到第五页:-D
myFile = read_file(r"Path/To/Your/File")
header_line = "id RegionName TypeSt TypePD TypeCode"
for line in myFile:
data = dict(zip(header.split("\t"), line.split("\t")))
# Here's a dictionary of the data for the current row
# You can access the elements of the row by name as follows in the filter example:
if data["TypePD"].lower() == "N":
continue
.....