首页 > 解决方案 > 用一组字符串重新索引熊猫系列正在删除系列中的原始数据

问题描述

我有一个名为 day_counts 的系列,它通常包含 7 个值,但看起来像这样。0 对应于星期一到 6,星期日。

Name: dow, dtype: int64
0    332
1    722
2    721

但是索引需要长 7 个值(一周中的几天),所以我重新索引系列,但使用字符串列表作为索引。代码如下所示(_scrobbles 是从 csv 文件读取的数据帧):

_scrobbles = self.scrobbles.query('month == ' + str(self.month))
_scrobbles['text_timestamp'] = pd.to_datetime(_scrobbles['text_timestamp'])
_scrobbles['dow'] = _scrobbles['text_timestamp'].map(lambda x: x.weekday())
data = _scrobbles['dow'].value_counts().sort_index()
day_counts = pd.Series(data=data)
new_index = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
day_counts_new = day_counts.reindex(index=new_index, fill_value=0)

这将创建新索引,但任何现有数据都被 0 覆盖,输出如下:

Mon    0
Tue    0
Wed    0
Thu    0
Fri    0
Sat    0
Sun    0
Name: dow, dtype: int64

它应该看起来像这样

Mon    332
Tue    722
Wed    721
Thu    0
Fri    0
Sat    0
Sun    0

有谁知道我如何保留现有数据?

有趣的是,如果我将索引设置为像这样的数字new_index = [0, 1, 2, 3, 4, 5, 6]

然后它按预期工作

谢谢

标签: pythonpandas

解决方案


>>> df = pd.DataFrame([332,722,721,0,0,0,0])
>>> df
     0
0  332
1  722
2  721
3    0
4    0
5    0
6    0
>>> new_index = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
>>> df.set_index(pd.Series(new_index))
       0
Mon  332
Tue  722
Wed  721
Thu    0
Fri    0
Sat    0
Sun    0

只需确保您的初始数据框与您的new_index. 但是正如您在帖子开头所说的那样;它通常包含 7 个值,所以不用担心。


推荐阅读