Python 提取字符串中特定列下的值
我的绳子如下Python 提取字符串中特定列下的值,python,string,python-3.x,pandas,Python,String,Python 3.x,Pandas,我的绳子如下 Module Available Used Remaining (Watts) (Watts) (Watts) ------ --------- -------- --------- 1 485.0 0.0 485.0 我需要提取Used下的值。我正试着分开绳子。有没有更好的方法来获取价值 使用str.split 演示: s = """Module Availab
Module Available Used Remaining
(Watts) (Watts) (Watts)
------ --------- -------- ---------
1 485.0 0.0 485.0
我需要提取
Used
下的值。我正试着分开绳子。有没有更好的方法来获取价值 使用str.split
演示:
s = """Module Available Used Remaining
(Watts) (Watts) (Watts)
------ --------- -------- ---------
1 485.0 0.0 485.0"""
for i in s.split("\n"):
if i.strip()[0].isdigit():
val = i.split()
print(val[2])
import re
val = re.findall("\d+\s+\d*\s+\d*\.\d*\s+\d*\.\d*\s+\d*\.\d*", s)
for v in val:
print(v.split()[2])
0.0
使用正则表达式:
s = """Module Available Used Remaining
(Watts) (Watts) (Watts)
------ --------- -------- ---------
1 485.0 0.0 485.0"""
for i in s.split("\n"):
if i.strip()[0].isdigit():
val = i.split()
print(val[2])
import re
val = re.findall("\d+\s+\d*\s+\d*\.\d*\s+\d*\.\d*\s+\d*\.\d*", s)
for v in val:
print(v.split()[2])
0.0
输出:
s = """Module Available Used Remaining
(Watts) (Watts) (Watts)
------ --------- -------- ---------
1 485.0 0.0 485.0"""
for i in s.split("\n"):
if i.strip()[0].isdigit():
val = i.split()
print(val[2])
import re
val = re.findall("\d+\s+\d*\s+\d*\.\d*\s+\d*\.\d*\s+\d*\.\d*", s)
for v in val:
print(v.split()[2])
0.0
也许这是一个过度杀戮,但您可以使用读取数据帧中的字符串,然后获得所需的值:
import io
import pandas as pd
your_string = io.StringIO("""Module Available Used Remaining
(Watts) (Watts) (Watts)
------ --------- -------- ---------
1 485.0 0.0 485.0""")
df = pd.read_csv(your_string,
sep=" ",
skipinitialspace=True,
skiprows=[1, 2])
df
将如下所示:
Module Available Used Remaining
0 1 485.0 0.0 485.0
及
将给您的0.0
p.S.:这是基于对“如何从字符串创建熊猫数据帧”问题的回答。这里可能有一些有用的东西: