首页 > 解决方案 > 如何一次切片熊猫数据框的所有元素?

问题描述

我的 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。为什么?这是怎么回事?我应该怎么做才能达到预期的行为?

标签: pythonpython-3.xpandasdataframedata-analysis

解决方案


您可以使用正则表达式来替换内容。

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 看上面的链接可以看到正则表达式的详细解释。

基本上,它使用方括号内的非空白内容作为值,并使用带有一些字符的任何字符串,后跟带有非空白字符的方括号作为目标字符串。


推荐阅读