繁体   English   中英

pandas DataFrame,如何将函数应用于特定列?

[英]pandas DataFrame, how to apply function to a specific column?

我已经阅读了DataFrame.apply的文档

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)¶ 沿 DataFrame 的输入轴应用函数。

那么,如何将函数应用于特定列?

In [1]: import pandas as pd
In [2]: data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
In [3]: df = pd.DataFrame(data)
In [4]: df
Out[4]: 
   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9
In [5]: def addOne(v):
...:        v += 1
...:        return v
...: 
In [6]: df.apply(addOne, axis=1)
Out[6]: 
   A  B   C
0  2  5   8
1  3  6   9
2  4  7  10

我想 addOne 到df['A']每个值,而不是所有列。 我怎么能用DataFrame.apply做到这DataFrame.apply

感谢您的帮助!

答案是,

df['A'] = df['A'].map(addOne)

也许你会更好地了解mapapplymapapply 的区别

但如果你坚持使用apply ,你可以尝试如下。

def addOne(v):
    v['A'] += 1
    return v

df.apply(addOne, axis=1)

一种简单的方法是:

df['A'] = df['A'].apply(lambda x: x+1)

您可以使用 .apply() 和 lambda 函数来解决此类问题。

考虑一下,你的数据框是这样的,

A | B | C
----------
1 | 4 | 7
2 | 5 | 8
3 | 6 | 9

您要应用的功能:

def addOne(v):
v += 1
return v

所以如果你这样写你的代码

df['A'] = df.apply(lambda x: addOne(x.A), axis=1)

你会得到:

A | B | C
----------
2 | 4 | 7
3 | 5 | 8
4 | 6 | 9

对于正在寻找允许管道连接的解决方案的任何其他人:

identity = lambda x: x

def transform_columns(df, mapper):
    return df.transform(
        {
            **{
                column: identity
                for column in df.columns
            },
            **mapper
        }
    )

# you can monkey-patch it on the pandas DataFrame (but don't have to, see below)
pd.DataFrame.transform_columns = transform_columns

(
    pd.DataFrame(data)
    .rename(columns={'A': 'A1'})   # just to demonstrate the motivation
    .transform_columns({'A1': add_one})
)

这还允许:

pd.DataFrame(data).transform_columns({
    'A': add_one,
    'B': add_two,
})

如果您不想修补 DataFrame,您始终可以将它与pipe一起使用:

pd.DataFrame(data).pipe(transform_columns, {'A': add_one})

不过,如果熊猫天真地支持这一点,那就太好了。

上面的片段是CC0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM