简体   繁体   English

基于操作现有列和引用对象创建新的数据框列

[英]Creating a new dataframe column based on manipulating existing column and refernce object

I have a dataset that contains flight information.我有一个包含航班信息的数据集。 One of the columns in the dataset is AirportFrom .数据集中的一列是AirportFrom This is a list of the 3 letter code attached to an airport.这是附加到机场的 3 个字母代码的列表。

I have a reference table that takes the 3 letter code and gives the state that the airport is in.我有一个参考表,它采用 3 个字母代码并给出了机场所在的状态。

I want to create a new column that takes all of the data from the AiportFrom and basically assigns the related State to the specific airport in the new column.我想创建一个新列,该列从AiportFrom获取所有数据,并基本上将相关状态分配给新列中的特定机场。

I have tried a few things that none of them seem to work correctly.我尝试了一些似乎都不能正常工作的东西。 I am getting an error in the last time I was trying to do it.我上次尝试这样做时遇到错误。

airportState = {
  'ATL': 'Georgia',
  'AUS': 'Texas',
  'BNA': 'Tennessee',
  'BOS': 'Massachusetts',
  'BWI': 'Washington',
  'CLT': 'North Carolina',
  'DAL': 'Texas',
  'DCA': 'Virginia',
  'DEN': 'Colorado',
  'DFW': 'Texas',
  'DTW': 'Michigan',
  'EWR': 'New Jersey',
  'FLL': 'Florida',
  'HNL': 'Hawaii',
  'HOU': 'Texas',
  'IAD': 'Virginia',
  'IAH': 'Texas',
  'JFK': 'New York',
  'LAS': 'Nevada',
  'LAX': 'California',
  'LGA': 'New York',
  'MCO': 'Florida',
  'MDW': 'Illinois',
  'MIA': 'Florida',
  'MSP': 'Minnesota',
  'MSY': 'Louisiana',
  'OAK': 'California',
  'ORD': 'Illinois',
  'PDX': 'Oregon',
  'PHL': 'Pennsylvania',
  'PHX': 'Arizona',
  'RDU': 'North Carolina',
  'SAN': 'California',
  'SEA': 'Washington',
  'SFO': 'California',
  'SJC': 'California',
  'SLC': 'Utah',
  'SMF': 'California',
  'STL': 'Missouri',
  'TPA': 'Florida',

}

here is the code I am trying to run:这是我要运行的代码:

dataset['StateFrom'] = airportState[dataset['AirportFrom']]

I know what the issue is, but I am not sure how to fix it.我知道问题是什么,但我不知道如何解决它。

Use map to substitute each value with the related State:使用map将每个值替换为相关的 State:

dataset['StateFrom'] = dataset['AirportFrom'].map(airportState)
print(dataset)

# Output
  AirportFrom StateFrom
0         PHX   Arizona
1         HNL    Hawaii
2         LGA  New York

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

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