python - 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 分配给上述记录未分配给它的记录。例如:奥本(奥本大学)当前状态是奥本,但我希望将其更新到阿拉巴马州,并且类似地用于阿拉巴马州以下的记录,直到代码遇到下一个州,即阿拉斯加
这是预期的输出
解决方案
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')
推荐阅读
- c# - 将 VBA 宏添加到 powerpoint
- c# - 编写自定义身份验证 + 我如何检查到哪个端点请求
- python - 将简单的 IDL 参数代码转换为 python 代码
- mysql - PhpMyAdmin 突然显示错误
- angular - 如何在源数组更改后从特定索引以角度启动引导轮播
- node.js - Webpack + Electron:如果应用程序没有它,为什么我需要“电子渲染器”脚本?
- ios - 我可以在没有 https 的情况下将我的应用程序发布到 App Store 吗?
- php - 我运行报告时需要保留三位小数
- php - 使用带有特定 postID 的 get_field 返回空
- reactjs - 使用 service worker 使服务器端渲染的 React 应用程序脱机工作