我有一个名为 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]
然后它就按预期工作了
谢谢
最佳答案
>>> 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 个值,所以不用担心。
关于python - 使用一组字符串对 pandas 系列进行索引会删除该系列中的原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980143/