首页 > 解决方案 > Pandas 数据清理以分配行下方的记录被分配一个特定的值

问题描述

在下面的代码中,我使用简单的数据操作来拆分列并删除不必要的字符。

input_uni_towns = pd.read_fwf("university_towns.txt", sep = " ", header = None)
uni_towns = input_uni_towns.rename(columns={0: "Raw_data"})
uni_towns['Cleaned'] = uni_towns["Raw_data"].replace(regex=True,to_replace=[r'\[[^()]*\]'],value=r'')
uni_towns[["State","University"]] = uni_towns.Cleaned.str.split("(",n=1,expand=True) 
uni_towns["University"] = uni_towns["University"].str.rstrip(')')
cleaned_uni_towns = uni_towns[["State","University"]]

在上述步骤之后,我想将 State 分配给上述记录未分配给它的记录。例如:奥本(奥本大学)当前状态是奥本,但我希望将其更新到阿拉巴马州,并且类似地用于阿拉巴马州以下的记录,直到代码遇到下一个州,即阿拉斯加

这是当前输出 电流输出

这是预期的输出

预期产出

标签: pythonpandasdata-cleaning

解决方案


NaN当大学不是时,您可以继续输入状态None(即与大学连续),然后NaN用最近的非NaN值填写状态。

df = pd.DataFrame({'Cleaned': ['Alabama', 'Auburn (Auburn University)', 'Alaska']})
df[['State', 'University']] = df.Cleaned.str.split('(', n = 1, expand = True)
df.University = df.University.str.rstrip(')')

df.State = np.where(df.University.map(lambda u: u is None), df.State, np.nan)
df.State = df.State.fillna(method = 'ffill')

推荐阅读