在 Pandas 中拆分并加入系列

Split and Join Series in Pandas

我在下面的数据框中有两个系列。第一个是将出现在第二个中的字符串,它将是 url 字符串。我想要做的是通过连接额外的字符来更改第一个系列,并将该更改应用于第二个字符串。

import pandas as pd
#import urlparse

d = {'OrigWord' : ['bunny', 'bear', 'bull'], 'WordinUrl' : ['http://www.animal.com/bunny/ear.html', 'http://www.animal.com/bear/ear.html', 'http://www.animal.com/bull/ear.html'] }

df = pd.DataFrame(d)

def trial(source_col, dest_col):
    splitter = dest_col.str.split(str(source_col))
    print type(splitter)
    print splitter
    res = 'angry_' + str(source_col).join(splitter)
    return res

df['Final'] = df.applymap(trial(df.OrigWord, df.WordinUrl))

我正在尝试 find the string from the source_col,然后 dest_col 中的字符串 split,然后对 dest_col 中的字符串进行更改。在这里,我将它作为一个名为 Final 的新系列,但我宁愿就地取材。我认为主要问题是 splitter 变量,它不起作用以及函数的应用。

结果应如下所示:

      OrigWord                                   WordinUrl
  angry_bunny  http://www.animal.com/angry_bunny/ear.html
  angry_bear   http://www.animal.com/angry_bear/ear.html
  angry_bull   http://www.animal.com/angry_bull/ear.html

apply 并非真正设计用于应用于同一行中的多个列。你可以做的是改变你的函数,让它接受一个系列,然后将 source_col、dest_col 分配给系列中的适当值。一种方法如下:

def trial(x):
    source_col = x["OrigWord"]
    dest_col = x['WordinUrl' ]
    splitter = str(dest_col).split(str(source_col))
    res = splitter[0] + 'angry_' + source_col + splitter[1]
    return res


df['Final'] = df.apply(trial,axis = 1 )

而不是使用 split,您可以使用 replace 方法将 angry_ 添加到相应的来源:

def trial(row):
    row.WordinUrl = row.WordinUrl.replace(row.OrigWord, "angry_" + row.OrigWord)
    row.OrigWord = "angry_" + row.OrigWord
    return row

df.apply(trial, axis = 1)

    OrigWord    WordinUrl
0   angry_bunny http://www.animal.com/angry_bunny/ear.html
1   angry_bear  http://www.animal.com/angry_bear/ear.html
2   angry_bull  http://www.animal.com/angry_bull/ear.html

这是另一种方法:

df['WordinUrl'] = (df.apply(lambda x: x.WordinUrl.replace(x.OrigWord,
                                                          'angry_' + x.OrigWord), axis=1))

In [25]: df
Out[25]:
  OrigWord                                   WordinUrl
0    bunny  http://www.animal.com/angry_bunny/ear.html
1     bear   http://www.animal.com/angry_bear/ear.html
2     bull   http://www.animal.com/angry_bull/ear.html