Python 将函数应用于my dataframe中的所有列

Python 将函数应用于my dataframe中的所有列,python,pandas,Python,Pandas,我无法将自定义函数应用于数据帧: df = pd.DataFrame({ "a": ["related-1", "related-0", "related-1"], "b": ["request-1", "request-0", "request-1"], "c": [&

我无法将自定义函数应用于
数据帧

df = pd.DataFrame({
        "a": ["related-1", "related-0", "related-1"],
        "b": ["request-1", "request-0", "request-1"],
        "c": ["offer-1", "offer-0", "offer-1"],
    })

def clean_column(df, column):
    return df[column].apply(lambda x: re.sub(".*-", "", x)).astype("int64")

clean_column(df, "a") # This works
我想将此函数应用于多列:

df.applymap(lambda x: clean_column(df, x))
错误:
KeyError:'related-1'


现在确定我做错了什么,有人能告诉我这不起作用的原因吗?

只需将您的函数应用于所有列:

for i in df.columns:
    clean_column(df, i)

请注意,这不会更新df本身,如果您希望

apply
将整个列作为输入,而不仅仅是名称,则必须更改函数。所以你想要:

def clean_column(column):
    return column.apply(lambda x: re.sub(".*-", "", x)).astype("int64")

df.apply(clean_column)
但是,在您的情况下,您需要为每一列再次应用
。换句话说,您希望将函数应用于所有单元格。即
applymap

df.applymap(lambda x: re.sub(".*-", "", x)).astype("int64")
df.applymap(lambda x: re.sub(".*-", "", x)).astype("int64")
输出:

   a  b  c
0  1  1  1
1  0  0  0
2  1  1  1

实际上,您可以使用: