在Python中,如何从字符串中删除一些字符或仅从中提取一些行?

在Python中,如何从字符串中删除一些字符或仅从中提取一些行?,python,pandas,dataframe,Python,Pandas,Dataframe,我使用熊猫来接收实时黄金价格,我只想清理输出,使其看起来好看和可读请帮我做这个 我的代码: import pandas as pd d = pd.read_html('http://www.livepriceofgold.com/pakistan-gold-price.html') type(d) a=len(d) i=1 df = d[3] finalString=df.to_string() print(finalString) 输出为: 0

我使用熊猫来接收实时黄金价格,我只想清理输出,使其看起来好看和可读请帮我做这个

我的代码:

import pandas as pd
d = pd.read_html('http://www.livepriceofgold.com/pakistan-gold-price.html')
type(d)
a=len(d)
i=1
df = d[3]
finalString=df.to_string()
print(finalString) 
输出为:

     0                                 1             2
0 NaN  Gold Rate in PKR Pakistani rupee          Rate
1 NaN         Gold Rate per Gram in PKR      7 889.65
2 NaN           Gold Rate per Oz in PKR    245 368.02
3 NaN           Gold Rate per KG in PKR  7 889 646.96
4 NaN         Gold Rate per Tola in PKR     92 023.26
我想要这种类型的输出:

Gram in PKR:      7 889.65
Oz in PKR  :      245 368.02
KG in PKR  :      7 889 646.96
Tola in PKR:     92 023.26

或者只提取变量中的速率

您可以为列名称中的第一行数据添加
header=0
参数,为在第一步中删除空格添加
数千='

然后通过索引删除第一列,设置新列名称并通过以下方式更改
Text
列中的值:


您可以将第一行数据的
header=0
参数添加到列名称中,并在第一步中删除空格

然后通过索引删除第一列,设置新列名称并通过以下方式更改
Text
列中的值:


到目前为止,我已使用此函数删除所有内容,然后拆分这些字符串,并使用拆分函数提取所需的值

 fs=fs.replace("Gold Rate per Gram in PKR","")
    fs=fs.replace("Gold Rate per Oz in PKR","")
    fs=fs.replace("Gold Rate per KG in PKR","")
    fs=fs.replace("Gold Rate per Tola in PKR","")
    fs=fs.replace("Gold Rate in PKR Pakistani rupee","")
    fs=fs.replace("Rate","")
    fs=fs.replace("0 NaN","")
    fs=fs.replace("1 NaN","")
    fs=fs.replace("2 NaN","")
    fs=fs.replace("3 NaN","")
    fs=fs.replace("4 NaN","")
    #print(fs.split())
    single= fs.split()

到目前为止,我已使用此函数删除所有内容,然后拆分这些字符串,并使用拆分函数提取所需的值

 fs=fs.replace("Gold Rate per Gram in PKR","")
    fs=fs.replace("Gold Rate per Oz in PKR","")
    fs=fs.replace("Gold Rate per KG in PKR","")
    fs=fs.replace("Gold Rate per Tola in PKR","")
    fs=fs.replace("Gold Rate in PKR Pakistani rupee","")
    fs=fs.replace("Rate","")
    fs=fs.replace("0 NaN","")
    fs=fs.replace("1 NaN","")
    fs=fs.replace("2 NaN","")
    fs=fs.replace("3 NaN","")
    fs=fs.replace("4 NaN","")
    #print(fs.split())
    single= fs.split()