简体   繁体   中英

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. I have a pandas dataframe like this: 在此处输入图像描述

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. If your base dataframe is called df , then:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM