- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试阅读人口普查 building permits text file有几行如下所示。有时,描述字段太长会导致行中出现换行符——这会搞砸 pandas。
533 45220 Tallahassee, FL 1613 810
999 13980 Blacksburg-Christiansburg-Radford,
VA 543 455
108 11100 Amarillo, TX 740 718
下面的代码会将文件读入 pandas——但是很多行都被移动了。你如何解析这样的文件文本文件?非常感谢。
testdf = pd.read_table('./csv/bldg_permits/metro/tb3u2016.txt', header='infer',
encoding="ISO-8859-1",skiprows=9,
delimiter = '\s+', skipinitialspace=True,
error_bad_lines=False)
最佳答案
作为 read_csv()
的一部分,Pandas 将无法像那样将行拼凑在一起。
我建议做第一遍来清理数据(分隔符也是一个问题),然后第二遍加载到 Pandas 中。
首先,从 URL 中获取数据(我使用的是 requests
,但任何 URL 解析器都可以):
import pandas as pd
import re
import requests
url = "https://www.census.gov/construction/bps/txt/tb3v2016.txt"
r = requests.get(url)
现在遍历行,将每一行写入lines
。
lines = []
begin_data = 10
backup_by = 1
for i, l in enumerate(r.text.split("\n")[begin_data:]):
line = (pd.Series(l).str.replace("(,|,\\*) ", "\\1_")
.str.replace("([A-z\\.]) ([A-z])", "\\1_\\2", n=-1))
if line.str.match("\d")[0]: # normal line
lines.append(line[0])
elif len(lines) > 0: # not a normal line, add to previous line
lines[i-backup_by] = lines[i-backup_by].strip() + line[0].strip()
backup_by += 1
fname = "census_data.txt"
f = open(fname, "w")
_ = [print(line, file=f) for line in lines]
上面 block 的注释:
\s+
分隔符将此表读入 Pandas,因此当空格不是列分隔符的一部分时,请将空格替换为 _
。我们正在特别寻找其中两种极端情况:
亚历山大,洛杉矶
--> 亚历山大,_LA
明尼阿波利斯 - 圣。保罗-布卢明顿
--> 明尼阿波利斯-圣保罗-布卢明顿
行
的索引。每次我们迭代一行原始数据并且不向 lines
添加新行时,我们的循环计数器 (i
) 和lines
中的最后一个元素递增 1。因此我们使用计数器 (backup_by
) 计算出要附加到的 lines
的正确索引。现在将清理后的文本文件读入 Pandas:
colnames = ["CSA", "CBSA", "Name", "Total", "1 Unit", "2 Units",
"3 and 4 Units", "5 Units or more"]
df = pd.read_table(fname, header=None, names=colnames, encoding="ISO-8859-1",
engine='python', delim_whitespace=True, skipfooter=3)
df.head()
CSA CBSA Name Total 1 Unit 2 Units \
0 999 10180 Abilene,_TX 55593 55193 400
1 184 10420 Akron,_OH 226669 226169 0
2 999 10500 Albany,_GA 28679 23686 0
3 440 10540 Albany,_OR 98763 97926 0
4 104 10580 Albany-Schenectady-Troy,*_NY 512058 361454 10605
3 and 4 Units 5 Units or more
0 0 0
1 500 0
2 360 4633
3 0 837
4 26585 113414
此时,如果需要,您可以返回并删除插入到 Name
字段中的空格的 _
占位符。
关于python - 如何将一行读入 Pandas——已被返回字符打破,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45910343/
这是主函数,其中还调用了 9 个函数。我将向您展示另一个函数,以便您了解我的目标是什么。 int main() { char B[rows][columns]; char answer
每当我使用 preventDefault() 时,我通常将它放在事件处理程序的顶部,如下所示: $('#foo').on('click', function(e){ e.preventDefaul
我想要实现的是用户输入一个值,然后输入一个测量值。然后将其放置为最小、最大或介于两者之间。保留输入了多少个值的计数。以及以米为单位的所有值的总和。 程序最初可以运行,但是当我输入换行符时,程序会重复同
我无法打破 while 循环。 "; $quizslots = mysql_query("SELECT * FROM quiz_slots WHERE `quizid`=$quizsectio
所以我将一个模板化的二叉树字典实现为一个继承自抽象字典类的类,我的添加函数有一个我无法弄清楚的问题。 基本上,我的树的节点具有键和值,以及指向其父节点、左子节点和右子节点的指针。节点的代码是 stru
我的代码应该在内容之间放置一个横幅,但它正在循环播放横幅。我需要它只显示一个横幅。我试过使用 return false;,就像这个例子一样,但它没有用: $(".newsitem_text").con
我有一个 Storyboard指定用于登录我的应用程序。我将其嵌入到 UINavigationController 中。登录到我的应用程序(并过渡到新的 Storyboard)后,我想“脱离”这个导航
我想知道是否可以在不使用 MCU 复位引脚上的外部复位按钮的情况下中断 while 循环并从特定位置重新启动代码。 下面是当“if”语句为真时我想中断的 while 循环,我正在使用 LCD,并想返回
所以我有这个问题,如果数组中的值高于输入值,它应该做一些事情然后停止循环并且不要触及数组中的剩余值。这是到目前为止的代码: const percentages = []; let enteredVal
我想在“div2”中打断长字,div2 和 div3 的宽度都不能大于父宽度(即 150px)。唯一有效的是 word-break: break-all 但这也会打断短词。 #div1{ di
我的数据库中有 3 个表。 PARENT_A 有一个“ID”主键列。 PARENT_B 有一个“ID”主键列。 CHILD 具有“PARENT_A_ID”和“PARENT_B_ID”外键列。它还有一个
在这个非常人为的示例中,我有一个包含 3 个元素的数组,我使用 .each() 对其进行循环。方法。 var vals = $w('foo bar baz'); vals.each( function
非常简单的示例代码(仅用于演示,没有任何用处): repeat { while (1 > 0) { for (i in seq(1, 100)) { break # usual
我有以下 promise : var aggregatePromise = () => { return new Promise((resolve, reject) => { Ei
我想检测表单的“输入”键而不让表单被提交。我如何打破这种关联? document.forms[0].onkeypress = function (event) { e = window.eve
这里是新手。我有一个 Ajax 函数,可以循环 3 个不同的请求。但是,如果第一个请求失败,我希望其他请求终止。我尝试放入“break”语句,但收到“非法的break语句”错误,我猜测是因为它不是直接
我有一个 Vector的 Vector不同长度的 s W .这些最后的向量包含 0 到 150,000 之间的整数,步长为 5,但也可以为空。我正在尝试计算每个向量的经验 cdf。我可以像这样计算这些
我想知道如何正确地打破 JS 中的 promise 链。 在这段代码中,我首先连接到数据库,然后检查集合是否已经有一些数据,如果没有则添加它们。不要关注一些 actionhero.js 代码..这里并
我有一个 Vector的 Vector不同长度的 s W .这些最后的向量包含 0 到 150,000 之间的整数,步长为 5,但也可以为空。我正在尝试计算每个向量的经验 cdf。我可以像这样计算这些
您可以使用 CompletableFuture 链接运行 block ,如下所示: CompletableFuture .supplyAsync(block1) .thenApply(
我是一名优秀的程序员,十分优秀!