def get_list_of_university_towns():
with open('university_towns.txt', 'r') as f:
data = (line.rstrip() for line in f)
lines = list(line for line in data if line)
thing = [lines]
indexx = [lines.index(line) for line in lines if '[edit]' in line]
numlist = [indexx]
wow = pd.DataFrame(thing)
tr = wow.T
tr.columns=['Region']
当我返回代码时,它返回:
""" Region
0 Alabama[edit]
1 Auburn (Auburn University)[1]
2 Florence (University of North Alabama)
3 Jacksonville (Jacksonville State University)[2]
4 Livingston (University of West Alabama)[2]
5 Montevallo (University of Montevallo)[2]
6 Troy (Troy University)[2]
7 Tuscaloosa (University of Alabama, Stillman Co...
8 Tuskegee (Tuskegee University)[5]
9 Alaska[edit]
10 Fairbanks (University of Alaska Fairbanks)[2]
11 Arizona[edit]
12 Flagstaff (Northern Arizona University)[6]
13 Tempe (Arizona State University)
14 Tucson (University of Arizona)
15 Arkansas[edit]
16 Arkadelphia (Henderson State University, Ouach...
如何获取它,以便我可以创建一个名为“州”的新列,该列将州名称附加到州的相应索引?索引部分的作用是将相应的索引返回到所有状态。我本质上希望它返回:
Region State
1 Auburn Alabama
2 Florence Alabama etc..
您应该能够迭代这些行,并使用 if-else 来确定该行是一个州还是一个地区。这些州似乎都包含 [edit]
标记,因此任何带有该标记的行都必须是一个州,否则它就是一个地区。
要创建数据框本身,我们可以创建一个元组列表,第一个元素是状态,第二个元素是区域(在适当清理文本后)。然后将列表传递给 pandas,它会优雅地将其转换为数据帧。
一个潜在的解决方案(虽然我不确定你的文本文件到底是什么样子):
data = []
for line in lines:
if '[edit]' in line:
state = line.replace('[edit]', '')
else:
region = line.split(' (')[0]
data.append((state, region))
df = pd.DataFrame(data, columns=['state', 'region'])
我是一名优秀的程序员,十分优秀!