I have been attempting turn 0 to 1 with pandas if the column name matches the year in each list. the last if
statement gives an error.
df
|--|start|end|2012|2013|2014|2015|2016|2017|2018|2018|2019| |0|2017/1/29|2019/9/10|0|0|0|0|0|0|0|0|0| |0|2012/1/30|2015/9/11|0|0|0|0|0|0|0|0|0| |0|2019/1/31|2019/10/5|0|0|0|0|0|0|0|0|0|
for index, row in df.iterrows(): s_year = int(row['start'][:4]) e_year = int(row['end'][:4]) l_years = [] l_years.append(s_year) while s_year < e_year: s_year += 1 l_years.append(s_year) for i in l_years: for column_name in df.columns.values: if i == column_name: df[index][column_name] = 1
Error
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2897 try: -> 2898 return self._engine.get_loc(casted_key) 2899 except KeyError as err: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 0 The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) 2 frames /usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2898 return self._engine.get_loc(casted_key) 2899 except KeyError as err: -> 2900 raise KeyError(key) from err 2901 2902 if tolerance is not None: KeyError: 0
https://stackoverflow.com/questions/67443716/how-to-put-a-value-to-each-row-of-the-column-name-that-matches-the-condition May 08, 2021 at 11:08AM
没有评论:
发表评论