我的 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)
编辑
replace pandas DataFrame
函数
将 to_replace 中给出的值替换为 value
目标字符串和需要替换的值可以是正则表达式。为此,您需要在参数中设置 regex=True
为 replace
https://regex101.com/r/7KCs6q/1 看上面的链接可以看到正则表达式的详细解释。
基本上,它使用方括号内的非空白内容作为值,并使用任何带有一些字符的字符串,后跟带有非空白字符的方括号作为目标字符串。
关于python - 如何一次切片 pandas dataframe 的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150718/