[英]iterate through columns pandas dataframe and create another column based on a condition
[英]Iterate on a pandas dataframe column and create a new column based on condition
您可以使用 map 或合并。 如果您的基础 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'])
或合并:
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
例如:
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'])
回报:
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.