Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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
列中所有值的条件字符串操作,Pandas,Python_Python_Pandas_String - Fatal编程技术网

列中所有值的条件字符串操作,Pandas,Python

列中所有值的条件字符串操作,Pandas,Python,python,pandas,string,Python,Pandas,String,给定这样的数据帧: import pandas as pd DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D',], 'COL2': ['gp.se', 'https://www.expressen.se/', 'http://friatider.se', 'http://www.klimatupplysningen.se']}) DF DF = pd.DataFrame({'COL1': ['A', 'B',

给定这样的数据帧:

import pandas as pd

DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D',], 
                   'COL2': ['gp.se', 'https://www.expressen.se/', 'http://friatider.se', 'http://www.klimatupplysningen.se']})
DF
DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D',], 
                       'COL2': ['gp.se', 'expressen.se', 'friatider.se', 'klimatupplysningen.se']})
    DF
我想检查COL2的每个值,并应用一些老式的字符串编辑方法,如下所示:

if string.starstwith('https://www'):
string.split('www.')[1][:-1])
elif string.startswith('http://') and string.endswith('/'):
string.split('www.')[1][:-1]
然后,我想在数据框的同一单元格中重新分配新编辑的字符串。结果应该是这样的:

import pandas as pd

DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D',], 
                   'COL2': ['gp.se', 'https://www.expressen.se/', 'http://friatider.se', 'http://www.klimatupplysningen.se']})
DF
DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D',], 
                       'COL2': ['gp.se', 'expressen.se', 'friatider.se', 'klimatupplysningen.se']})
    DF
有没有一种方法可以使用
df.loc
优雅地替换字符串,重用原始字符串的一部分,并应用我熟悉的if/else、startswith/endswith、string切片方法

我知道replace函数,但我更喜欢这种有条件的方式(我的实际df要大得多,有更多的值,我希望避免一个接一个地替换它们)

您可以使用,然后使用
/
(而不是像
http://www
):


另一种方法是使用regex

将熊猫作为pd导入
df=pd.DataFrame({'COL1':['A','B','C','D',],
'COL2':['gp.se','https://www.expressen.se/', 'http://friatider.se', 'http://www.klimatupplysningen.se']})
pattern=r'https{0,1}://w{0,3}\.{,1}'
打印(df['COL2'].str.replace(模式,').str.strip('/'))

这是另一个好的,谢谢!是第一个。需要?这不是第一个答案,效果很好。问得好!:)我使用.str表示并行性