[英]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.