【发布时间】:2020-09-02 10:27:47
【问题描述】:
我正在尝试解决来自 coursera 上 Introduction to data science 的问题:
返回城镇及其所在州的 DataFrame university_towns.txt 列表。 DataFrame 的格式应为: DataFrame([[“密歇根”,“安娜堡”],[“密歇根”,“伊普西兰蒂”]], columns=["State", "RegionName"])
The following cleaning needs to be done: 1. For "State", removing characters from "[" to the end. 2. For "RegionName", when applicable, removing every character from " (" to the end. 3. Depending on how you read the data, you may need to remove newline character '\n'.
我的脚本如下:
uni_towns = pd.read_csv('university_towns.txt', header=None, names={'RegionName'})
uni_towns['State'] = np.where(uni_towns['RegionName'].str.contains('edit'), uni_towns['RegionName'], '')
uni_towns['State'] = uni_towns['State'].replace('', np.nan).ffill()
import re
# Removing (...) from state names
uni_towns['RegionName'] = uni_towns['RegionName'].apply(lambda x: re.sub(r'\([^)]*\)', '', x))
split_string = "("
uni_towns['RegionName'] = uni_towns['RegionName'].apply(lambda x: x.split(split_string, 1)[0])
# Removing [...] from state names
uni_towns['RegionName'] = uni_towns['RegionName'].apply(lambda x: re.sub(r'\[[^\]]*\]', '', x))
uni_towns['State'] = uni_towns['State'].apply(lambda x: re.sub(r'\[[^\]]*\]', '', x))
uni_towns = pd.DataFrame(uni_towns,columns = ['State','RegionName']).sort_values(by=['State', 'RegionName'])
return uni_towns
第一行显然是关于读取文本文件,然后RegionName 中包含单词edit 的所有字段也是状态:
uni_towns['State'] = np.where(uni_towns['RegionName'].str.contains('edit'), uni_towns['RegionName'], '')
然后我从RegionName 的每一行中删除括号 () 和方括号 [] 之间的所有内容:
uni_towns['RegionName'] = uni_towns['RegionName'].apply(lambda x: re.sub(r'\([^)]*\)', '', x))
uni_towns['RegionName'] = uni_towns['RegionName'].apply(lambda x: re.sub(r'\[[^\]]*\]', '', x))
因此,如果一个值类似于Alabama[edit] 或Tuscaloosa (University of Alabama),它们将变为Alabama 和Tuscaloosa。
然后我对State 列做同样的事情,因为如果它包含[edit],我将一些值从RegionName 移到其中。
我正在使用以下内容,因为很少有行具有类似 ``Tuscaloosa (University of Alabamawhere there is only(` 并且它没有被正则表达式模式检测到:
uni_towns['RegionName'] = uni_towns['RegionName'].apply(lambda x: x.split(split_string, 1)[0])
最终结果为:567 rows × 2 columns
州区域名称
0 阿拉巴马州阿拉巴马州
1 阿拉巴马州奥本
2 阿拉巴马州佛罗伦萨
3 阿拉巴马州杰克逊维尔
...
564 威斯康星白水
551 威斯康星州威斯康星州
566 怀俄明州拉勒米
565 怀俄明州怀俄明州
虽然正确的结果应该是 `517 行 x 2 列。
查看txt 文件后,我看到某些行在读取时使用\n 连续两行,但脚本未检测到\n 之前的第二行仍在同一行内行。
这里是the text content。
【问题讨论】:
标签: python pandas data-science