Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 提取字符串中特定列下的值_Python_String_Python 3.x_Pandas - Fatal编程技术网

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.:这是基于对“如何从字符串创建熊猫数据帧”问题的回答。

这里可能有一些有用的东西: