我有一列字符串,我想转换成特定的数字。我目前的方法涉及使用for循环,但我觉得这不是Pandas的设计用途。有人能建议一个更优雅的解决方案,适用于多个列吗?
下面是我的代码-
import pandas as pd
data = [['mechanical@engineer', 'field engineer'], ['field engineer', 'lab_scientist'],
['lab_scientist', 'mechanical@engineer'], ['field engineer', 'mechanical@engineer'],
['lab_scientist','mechanical@engineer']]# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Job1', 'Job2'])
for index, row in df.iterrows():
if row['Job1']=="mechanical@engineer":
row['Job1'] = 0
elif row['Job1']=="field engineer":
row['Job1'] = 1
elif row['Job1'] == "lab_scientist":
row['Job1'] = 2
print(df.head())
2条答案
按热度按时间ppcbkaq51#
你只需要一张Map:
u0sqgete2#
为什么不使用
replace
函数而不是for
循环?输出将是: