字典不处理多个值

Dictionary not handling multiple values

我正在尝试创建州和城市的数据框。

我正在阅读的 table 中的每个州名都以字母 [edit] 结尾,另一方面,城市要么以 (text)[人数]

我使用正则表达式删除了括号和方括号内的文本,将州保存在一个州列表中,将城市保存在另一个城市列表中。

然后我将这两个列表转换成字典,其中州为键,城市为值。

但是有 517 个城市,当我这样做时我失去了 467 个城市。我猜是因为目前我不允许我的字典处理多个值。我的目标是创建一个 517x2 维度的数据框,其中包含州列和城市列(与其州匹配的城市)。如果我从这本字典创建一个数据框,我只会得到 50x2 而不是 512x2 尺寸。

我的问题是; i.) 我的推理是否正确,ii.) 我应该如何考虑解决这个问题 problem/how 我应该如何解决它,iii.) 是我编写的实现最终目标的最有效方法的代码

import pandas as pd
import numpy as np
import re
state = []
city = []
with open("university_towns.txt","r") as i:
    uni = i.readlines()
for st in uni:
    if "[edit]"in st:
        state.append(re.sub("[\[].*?[\]]\s", "", st))
    else:
        city.append(re.sub("[\(\[].*?[\)\]]\s", "", st))
city_st = dict(zip(state,city))
#need to take the key-value pairs/items from the dictionary
s = pd.Series(city_st, name ='RegionName')
s.index.name = 'State'
s = s.reset_index()
s

ADD:不太确定如何为这个问题添加相关数据

注意:

city_st = dict(zip(state,city))

由于多值,此操作可能会导致结果数量减少。

你可以直接使用

aa = pd.dataframe({'state': state,'city': city})
aa['State' ] = range(aa.shape[0])

然后使用pivot_table来融化你的数据