简体   繁体   English

"将函数应用于熊猫数据框中列的每一对元素"

[英]Applying a function to each couple of elements of a column in a pandas data frame

I have the need to create a new column of a pandas data frame applying a function to each couple of consecutive elements.The first element if the new column has to be a nan.我需要创建一个熊猫数据框的新列,将函数应用于每对连续元素。如果新列必须是 nan,则第一个元素。 Let's assume that the function is the sum of the elements divided by 3. Here's an example to clarify what I need:让我们假设该函数是元素的总和除以 3。这是一个示例来说明我需要什么:

a b new_column
1 2 nan
3 4 2
5 5 3
# We are going to assign a new column
df = df.assign(
    # based on a function that we will apply
    new_column = df.apply(
        # the function adds each value in column a and b and divide it by 3 (without rest)
        lambda row: (row["a"] + row["b"]) // 3, axis = 1
    )
)

# Finally we delete our first entry
df["new_column"][0] = ""

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

相关问题 将功能应用于熊猫数据帧的每一行-快速 - Applying function to each row of pandas data frame - with speed 将 function 应用于 Pandas 中的数据帧返回 UnboundLocalError - Applying function to a data frame in Pandas returns UnboundLocalError 将函数应用于每两行的每个数组 - Applying a function to each array of every couple of rows 将年龄函数应用于数据框列 - Applying age function to data-frame column 如何比较 pandas 数据框列中分隔字符串中的每个元素与 python 列表 object 元素 - How to compare the each elements in the delimited string in pandas data frame column with a python list object elements 将公式应用于每个值,遍历熊猫数据框 - Looping over pandas data frame applying formula to each value 如果列元素是一个集合,如何从 pandas 数据框列中获取每个值的计数? - How do I get count of each value from a pandas Data Frame column if the column elements is a set? 在整个数据框中查找第一列元素并返回每行前面的第一列值(熊猫) - find first column elements in entire data frame and return first column values in front of each row(Pandas) 将函数应用于熊猫中分组数据的单个列 - Applying function to a single column of a grouped data in pandas 使用 pandas 重命名数据框列中的元素 - rename elements in a column of a data frame using pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM