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