dataframe 数据怎么能把索引问题

2020-07-31 14:18:56 +08:00
 QGabriel
数据如下:
ts_code trade_date open high low close pre_close change pct_chg vol amount
0 600585.SH 20200729 59.60 60.80 59.05 60.68 59.90 0.78 1.3022 319148.23 1923818.350
1 600585.SH 20200728 60.18 60.95 59.45 59.90 59.76 0.14 0.2343 284117.71 1711289.743
2 600585.SH 20200727 59.62 60.90 59.14 59.76 58.85 0.91 1.5463 362054.35 2171456.775
3 600585.SH 20200724 60.46 60.94 58.20 58.85 61.05 -2.20 -3.6036 443699.05 2636469.588
4 600585.SH 20200723 60.08 61.50 59.11 61.05 60.97 0.08 0.1312 437532.84 2641867.877
.. ... ... ... ... ... ... ... ... ... ... ...
133 600585.SH 20200108 53.00 53.38 52.60 52.69 53.48 -0.79 -1.4772 232324.76 1228341.855
134 600585.SH 20200107 53.12 54.13 53.12 53.48 53.32 0.16 0.3001 234783.33 1256641.148
135 600585.SH 20200106 54.01 54.54 53.05 53.32 54.68 -1.36 -2.4872 343560.81 1845565.954
136 600585.SH 20200103 56.00 56.10 54.44 54.68 55.80 -1.12 -2.0072 288642.12 1585798.292
137 600585.SH 20200102 55.30 57.75 55.03 55.80 54.80 1.00 1.8248 411235.67 2306726.977

设置 df.sort_index(ascending = True) 或 false
索引 0 都是指向 20200729 这行数据
怎么能把 0 指向 20200102 这行数据呢?
1522 次点击
所在节点    Python
4 条回复
capallen
2020-07-31 14:25:00 +08:00
先按照 trade_date 排序,然后 reset_index 就好了,参考:
```python
df = df.sort_values(by='trade_date')
df = df.reset_index(drop=True)
```
QGabriel
2020-07-31 14:26:24 +08:00
@capallen 感谢!
QGabriel
2020-07-31 14:46:40 +08:00
@capallen 你好 再问个问题
按照你的代码
df 数据的顺序对了

close = df['close']
date = df['trade_date']

之后再 print 怎么又回到降序了呢?

df 重新排序后:
ts_code trade_date open high low close pre_close change pct_chg vol amount
0 600585.SH 20200102 55.30 57.75 55.03 55.80 54.80 1.00 1.8248 411235.67 2306726.977
1 600585.SH 20200103 56.00 56.10 54.44 54.68 55.80 -1.12 -2.0072 288642.12 1585798.292
2 600585.SH 20200106 54.01 54.54 53.05 53.32 54.68 -1.36 -2.4872 343560.81 1845565.954
3 600585.SH 20200107 53.12 54.13 53.12 53.48 53.32 0.16 0.3001 234783.33 1256641.148
4 600585.SH 20200108 53.00 53.38 52.60 52.69 53.48 -0.79 -1.4772 232324.76 1228341.855
.. ... ... ... ... ... ... ... ... ... ... ...
133 600585.SH 20200723 60.08 61.50 59.11 61.05 60.97 0.08 0.1312 437532.84 2641867.877
134 600585.SH 20200724 60.46 60.94 58.20 58.85 61.05 -2.20 -3.6036 443699.05 2636469.588
135 600585.SH 20200727 59.62 60.90 59.14 59.76 58.85 0.91 1.5463 362054.35 2171456.775
136 600585.SH 20200728 60.18 60.95 59.45 59.90 59.76 0.14 0.2343 284117.71 1711289.743
137 600585.SH 20200729 59.60 60.80 59.05 60.68 59.90 0.78 1.3022 319148.23 1923818.350

close = df['close']
0 60.68
1 59.90
2 59.76
3 58.85
4 61.05
...
133 52.69
134 53.48
135 53.32
136 54.68
137 55.80
QGabriel
2020-07-31 15:20:16 +08:00
@capallen 忽略吧~ 我弄错了 不好意思

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/694631

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX