简体   繁体   English

在 pandas dataframe 列上迭代并根据条件创建一个新列

[英]Iterate on a pandas dataframe column and create a new column based on condition

I am new to Pandas and I have some issues developing my code.我是 Pandas 的新手,我在开发代码时遇到了一些问题。 I have a pandas dataframe like this:我有一个 pandas dataframe 像这样: 在此处输入图像描述

What I want to do is creating a new column "Weight per meter" and then check each element on "Design Section" column and if this element equals to one of the elements on "Section Name" column, the value of "Weight per meter" column will be the corresponding element in "Weight Per Unit Length".我想要做的是创建一个新列“每米重量”,然后检查“设计部分”列中的每个元素,如果该元素等于“部分名称”列中的元素之一,则“每米重量”的值" 列将是“每单位长度的重量”中的相应元素。 Some thing like this:像这样的一些事情:

在此处输入图像描述

How should I do this?我该怎么做?

You can do it with a map or merge.您可以使用 map 或合并。 If your base dataframe is called df , then:如果您的基础 dataframe 称为df ,则:

df['Weight per meter'] = df['Design Section'].map(df[['Section Name','Weight Per Unit Length']].set_index('Section Name').to_dict()['Weight Per Unit Length'])

Or with a merge:或合并:

df['Weight per meter'] = df[['Design Section']].merge(df[['Section Name','Weight Per Unit Length']].drop_duplicates(),left_on='Design Section',right_on='Section Name',how='left')['Weight Per Unit Length

For example:例如:

df = pd.DataFrame({'Col 1':['A','B','C','D','E'],
                   'Col 2':[1,2,3,4,5],
                   'Col 3':['G','B','C','D','F']})

df['Col 4'] = df['Col 3'].map(df[['Col 1','Col 2']].set_index('Col 1').to_dict()['Col 2'])

Returns:回报:

  Col 1  Col 2 Col 3  Col 4
0     A      1     G    NaN
1     B      2     B    2.0
2     C      3     C    3.0
3     D      4     D    4.0
4     E      5     F    NaN

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

相关问题 遍历列 pandas dataframe 并根据条件创建另一列 - iterate through columns pandas dataframe and create another column based on a condition Pandas 数据框根据另一列的条件创建新行 - Pandas dataframe create new rows based on condition from another column 如何根据 Pandas dataframe 中的日期值和条件创建新列 - How to create a new column based on Date Values & Condition in Pandas dataframe 合并两个 pandas dataframe 并根据条件创建一个新的二进制列 - Merge two pandas dataframe and create a new binary column based on condition Pandas 根据来自另一个 dataframe 的计数和条件创建新列 - Pandas Create new column based on a count and a condition from another dataframe 如何根据条件在 pandas dataframe 中创建一个新列? - How to create a new column in pandas dataframe based on a condition? 根据 dataframe 查询条件在 Pandas 中创建列 - Create column in Pandas based on dataframe query condition 根据条件在pandas数据框中创建列 - Create column in pandas dataframe based on condition 检查特定列是否大于另一列并根据 pandas dataframe 中的条件创建新列 - Check if specific column is greater than another column and create a new column based on condition in pandas dataframe 根据条件在 pandas 中创建新列 - create new column in pandas based on condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM