简体   繁体   English

通过对每一行进行操作,在数据框中创建列的“pandas”方法是什么?

[英]What is the `pandas` way to create a column in a dataframe by operating on each row?

I have an apply function that operates on each row in my dataframe. 我有一个apply函数,可以在我的数据帧中的每一行上运行。 The result of that apply function is a new value. apply函数的结果是一个新值。 This new value is intended to go in a new column for that row. 此新值旨在进入该行的新列。

So, after applying this function to all of the rows in the dataframe, there will be an entirely new column in that dataframe. 因此,在将此函数应用于数据框中的所有行之后,该数据框中将有一个全新的列。

How do I do this in pandas ? 我怎么在pandas这样做?

Two ways primarily: 主要有两种方式:

df['new_column'] = df.apply(my_fxn, axis=1)

or 要么

df = df.assign(new_column=df.apply(my_fxn, axis=1))

If you need to use other arguments, you can pass them to the apply function, but sometimes it's easier (for me) to just use a lambda: 如果你需要使用其他参数,你可以将它们传递给apply函数,但有时候(对我来说)使用lambda更容易:

df['new_column'] = df.apply(lambda row: my_fxn(row, global_dict), axis=1)

Additionally, if your function can operate on arrays in a vectorized fashion, you could just do: 此外,如果您的函数可以以矢量化方式在数组上运行,您可以这样做:

df['new_column'] = my_fxn(df['col1'], df['col2'])

暂无
暂无

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

相关问题 根据另一行的条件在 Pandas dataframe 中创建新列的最佳方法是什么? - What is the optimal way to create a new column in Pandas dataframe based on conditions from another row? 删除列并为每个删除的列创建唯一的行 Pandas Dataframe - Remove Columns And Create Unique Row For Each Removed Column Pandas Dataframe 为每一行运行一个函数并创建一个新的 Column Pandas Dataframe - Run a function for each row and create a new Column Pandas Dataframe pandas 为 dataframe 的每一行计算新值的方法是什么? - What's the pandas way of computing a new value for each row of a dataframe? 有没有办法向pandas数据框添加新列,将新列的每个唯一值附加到数据帧的每个现有行? - Is there a way to add a new column to a pandas dataframe, appending each unique value of the new column to every existing row of the dataframe? Pandas,Dataframe,每行的条件总和 - Pandas, Dataframe, conditional sum of column for each row 对熊猫数据框中每一行进行排序的最快方法 - Fastest way to sort each row in a pandas dataframe 为 pandas dataframe 的每一行替换列中的字符串 - Replace a string in a column for each row of a pandas dataframe 为熊猫数据框中的每一行创建热图 - create heatmap for each row in pandas dataframe 如何从 pandas dataframe 中的当前行中减去前一行以创建一个新列,以每个名称重新启动进程? - How to subtract previous row from current row in a pandas dataframe to create a new column restarting the process with each name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM