【发布时间】:2021-09-11 06:10:08
【问题描述】:
我有这样的数据,我想用前一行 groupby reg 值填充 Na。例如。第二行可以是SHE,第四行是XMN,由于最后两行的schedule_from相同,所以我选择不使用SHA填充第五行的Na
| reg | schedule_from | schedule_to |
|---|---|---|
| X-346 | CAN | SHE |
| X-346 | NaN | ZUH |
| A-583 | CTU | NaN |
| A-583 | XMN | SZX |
| T-777 | SHA | NaN |
| T-777 | SHA | CVG |
我累了一些编码,里面也显示了错误
KeyError Traceback (most recent call last)
<ipython-input-20-19798ba7d29d> in <module>
4 if asub['schedule_from'][ind] != asub['schedule_from'][ind-1]:
5 if (pd.isnull(asub['schedule_from'][ind])== True)&(pd.isnull(asub['schedule_to'][ind-1])==False):
----> 6 asub.groupby(['aircraft_registration_no']).apply(lambda x: x['schedule_from'][ind] == x['schedule_to'][ind-1])
7 # asub.groupby(['aircraft_registration_no']).apply(lambda x: x['schedule_to'][ind] == x['schedule_from'][ind+1])
~\anaconda3\lib\site-packages\pandas\core\groupby\groupby.py in apply(self, func, *args, **kwargs)
857 with option_context("mode.chained_assignment", None):
858 try:
--> 859 result = self._python_apply_general(f, self._selected_obj)
860 except TypeError:
861 # gh-20949
~\anaconda3\lib\site-packages\pandas\core\groupby\groupby.py in _python_apply_general(self, f, data)
890 data after applying f
891 """
--> 892 keys, values, mutated = self.grouper.apply(f, data, self.axis)
893
894 return self._wrap_applied_output(
~\anaconda3\lib\site-packages\pandas\core\groupby\ops.py in apply(self, f, data, axis)
211 # group might be modified
212 group_axes = group.axes
--> 213 res = f(group)
214 if not _is_indexed_like(res, group_axes):
215 mutated = True
<ipython-input-20-19798ba7d29d> in <lambda>(x)
4 if asub['schedule_from'][ind] != asub['schedule_from'][ind-1]:
5 if (pd.isnull(asub['schedule_from'][ind])== True)&(pd.isnull(asub['schedule_to'][ind-1])==False):
----> 6 asub.groupby(['aircraft_registration_no']).apply(lambda x: x['schedule_from'][ind] == x['schedule_to'][ind-1])
7 # asub.groupby(['aircraft_registration_no']).apply(lambda x: x['schedule_to'][ind] == x['schedule_from'][ind+1])
~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
880
881 elif key_is_scalar:
--> 882 return self._get_value(key)
883
884 if is_hashable(key):
~\anaconda3\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
987
988 # Similar to Index.get_value, but we do not fall back to positional
--> 989 loc = self.index.get_loc(label)
990 return self.index._get_values_for_loc(self, loc, label)
991
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
-> 2897 raise KeyError(key) from err
2898
2899 if tolerance is not None:
KeyError: 7
【问题讨论】:
标签: python pandas conditional-statements pandas-groupby