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. Let's assume that the function is the sum of the elements divided by 3. Here's an example to clarify what I need:
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] = ""
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.