python - 如何一次切片熊猫数据框的所有元素?
问题描述
我的 Pandas 数据框中存储了以下数据:
Factor SimTime RealTime SimStatus
0 Factor[0.48] SimTime[83.01] RealTime[166.95] Paused[F]
1 Factor[0.48] SimTime[83.11] RealTime[167.15] Paused[F]
2 Factor[0.49] SimTime[83.21] RealTime[167.36] Paused[F]
3 Factor[0.48] SimTime[83.31] RealTime[167.57] Paused[F]
我想创建一个新的数据框,其中只有 [] 中的所有内容。
我正在尝试使用以下代码:
df = dataframe.apply(lambda x: x.str.slice(start=x.str.find('[')+1, stop=x.str.find(']')))
但是,我看到的df
只是 NaN。为什么?这是怎么回事?我应该怎么做才能达到预期的行为?
解决方案
您可以使用正则表达式来替换内容。
df.replace(r'\w+\[([\S]+)\]', r'\1', regex=True)
编辑
替换熊猫的功能DataFrame
Replace values given in to_replace with value
目标字符串和需要替换的值可以是正则表达式。为此,您需要将regex=True
参数设置为replace
https://regex101.com/r/7KCs6q/1 看上面的链接可以看到正则表达式的详细解释。
基本上,它使用方括号内的非空白内容作为值,并使用带有一些字符的任何字符串,后跟带有非空白字符的方括号作为目标字符串。
推荐阅读
- python - 声明在循环内更新自身的 DataFrame 的最佳方法是什么?
- typescript - 通过 v-for 循环中的 v-model 改变 Vuex 存储
- python - 如何让我的 2x2 子图在 python 中是正方形的
- google-apps-script - 在 Google Scripts 中从多个 Google 表格查询的最佳方法是什么:索引列
- python - 如何迭代列表项以存储为字典并将其写入 json?
- c++ - C ++合并排序检查以查看数字是否在列表中
- ios - CoreML中输入/输出类型都是multiArray,如何处理
- reactjs - 我如何循环 React 引导轮播项目
- angular - Algolia AngularInstantSearch 分页和地图
- sql-server - 创建触发器以检查 SQL Server 中是否为同一天?