Python:pandas适用于地图

Fre*_*ter 4 python apply pandas

我很难理解究竟df.apply()是如何运作的.

我的问题如下:我有一个数据帧df.现在我想在几列中搜索某些字符串.如果在我要为找到字符串的每一行添加的任何列中找到该字符串,则为"标签"(在新列中).

我能够与解决问题mapapplymap(见下文).

但是,我希望更好的解决方案是使用, apply因为它将函数应用于整个列.

问题:这不可能使用apply吗?我的错误在哪里?

以下是我使用map和的解决方案applymap.

df = pd.DataFrame([list("ABCDZ"),list("EAGHY"), list("IJKLA")], columns = ["h1","h2","h3","h4", "h5"])
Run Code Online (Sandbox Code Playgroud)

解决方案使用 map

def setlabel_func(column):
    return df[column].str.contains("A")

mask = sum(map(setlabel_func, ["h1","h5"]))
df.ix[mask==1,"New Column"] = "Label"
Run Code Online (Sandbox Code Playgroud)

解决方案使用 applymap

mask = df[["h1","h5"]].applymap(lambda el: True if re.match("A",el) else False).T.any()
df.ix[mask == True, "New Column"] = "Label"
Run Code Online (Sandbox Code Playgroud)

因为apply我不知道如何将两列传递给函数/或者根本不理解机制;-)

def setlabel_func(column):
    return df[column].str.contains("A")

df.apply(setlabel_func(["h1","h5"]),axis = 1)
Run Code Online (Sandbox Code Playgroud)

上面给了我警觉.

'DataFrame'对象没有属性'str'

有什么建议?请注意,我的实际应用程序中的搜索功能更复杂,需要正则表达式功能,这就是我.str.contain首先使用的原因.

jez*_*ael 6

另一种解决方案是DataFrame.any用于True每行至少一个:

print (df[['h1', 'h5']].apply(lambda x: x.str.contains('A')))
      h1     h5
0   True  False
1  False  False
2  False   True

print (df[['h1', 'h5']].apply(lambda x: x.str.contains('A')).any(1))
0     True
1    False
2     True
dtype: bool
Run Code Online (Sandbox Code Playgroud)
df['new'] = np.where(df[['h1','h5']].apply(lambda x: x.str.contains('A')).any(1),
                     'Label', '')

print (df)
  h1 h2 h3 h4 h5    new
0  A  B  C  D  Z  Label
1  E  A  G  H  Y       
2  I  J  K  L  A  Label
Run Code Online (Sandbox Code Playgroud)
mask = df[['h1', 'h5']].apply(lambda x: x.str.contains('A')).any(1)
df.loc[mask, 'New'] = 'Label'
print (df)
  h1 h2 h3 h4 h5    New
0  A  B  C  D  Z  Label
1  E  A  G  H  Y    NaN
2  I  J  K  L  A  Label
Run Code Online (Sandbox Code Playgroud)


piR*_*red 5

pd.DataFrame.apply迭代每一列,将列作为 a 传递pd.Series给正在应用的函数。在您的情况下,您尝试应用的功能不适合在apply

这样做是为了让您的想法发挥作用

mask = df[['h1', 'h5']].apply(lambda x: x.str.contains('A').any(), 1)
df.loc[mask, 'New Column'] = 'Label'

  h1 h2 h3 h4 h5 New Column
0  A  B  C  D  Z      Label
1  E  A  G  H  Y        NaN
2  I  J  K  L  A      Label

?
Run Code Online (Sandbox Code Playgroud)