Python:pandas应用vs.map

2024-05-28 20:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解df.apply()到底是如何工作的。

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

我能用mapapplymap解决问题(见下文)。

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

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

这里是我使用mapapplymap的解决方案。

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

使用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"

使用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"

对于apply我不知道如何将这两列传递到函数中/或者可能根本不了解机制;-)

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

df.apply(setlabel_func(["h1","h5"]),axis = 1)

上面提醒我。

'DataFrame' object has no attribute 'str'

有什么建议吗?请注意,实际应用程序中的搜索函数更复杂,需要一个regex函数,这就是我首先使用.str.contain的原因。


Tags: 函数字符串mapdfcolumnmask解决方案h1
3条回答

另一种解决方案是使用^{}获取每行至少一个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

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

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

你可以这样做:

In [23]: df['new'] = np.where(df[['h1','h5']].apply(lambda x: x.str.contains('A'))
                                             .sum(1) > 0,
                              'Label', '')

In [24]: df
Out[24]:
  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

pd.DataFrame.apply遍历每个列,将列作为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

​

相关问题 更多 >

    热门问题