python - 用一组字符串重新索引熊猫系列正在删除系列中的原始数据
问题描述
我有一个名为 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 个值,所以不用担心。
推荐阅读
- javascript - 用户单击按钮后,将列表动态添加到现有列表集
- reactjs - 反应打字稿构造函数状态与属性
- ecmascript-6 - ES6扩展BaseClass而不调用构造函数,当我试图在我的子类中调用一个方法时抛出错误
- android - java-Android Studio [ClassNotFoundException]
- .net - 无法从 Linux 容器切换到 Windows 容器
- html - Bootstrap 4.1.2:想要将 Bootstrap 4.1.2 添加到我的项目中,使用包管理器 npm?
- javascript - 在 React 组件中渲染 JSON 数组
- opengl-es - 为什么没有 glBindBuffer 的 glVertexAttribPointer 也可以工作?
- python - PyQt5 QFrame 的实际大小
- selenium - 使用 Selenium webdriver 自动化 IE 时无法从全屏模式切换到最大化模式