使用重复项重命名索引

时间:2017-12-10 15:15:47

标签: python pandas dataframe indexing

import datetime
dates_list = ['2015-03-28 10:15:36.560000', '2015-03-28 11:35:17.820000',
           '2015-03-29 13:34:54.380000', '2015-03-29 14:10:41.900000',
           '2015-03-31 16:55:43.680000', '2015-03-31 16:57:58.320000',
           '2015-04-02 18:54:31.480000', '2015-04-02 19:46:46.580000',
           '2015-04-03 20:58:27.940000', '2015-04-03 21:30:05.600000']

df = pd.DataFrame(data=[1,2,3,np.nan,5,6,np.nan,np.nan,8,9],columns=['value'],index=[datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f') for date in dates_list])

df.index = df.index.date

df
Out[36]: 
            value
2015-03-28    1.0
2015-03-28    2.0
2015-03-29    3.0
2015-03-29    NaN
2015-03-31    5.0
2015-03-31    6.0
2015-04-02    NaN
2015-04-02    NaN
2015-04-03    8.0
2015-04-03    9.0

如何重命名索引以便我有

df
Out[36]: 
            value
0    1.0
0    2.0
1    3.0
1    NaN
2    5.0
2    6.0
3    NaN
3    NaN
4    8.0
4    9.0

2 个答案:

答案 0 :(得分:0)

使用factorize并按[0]选择第一个数组:

df.index = df.index.factorize()[0]

GroupBy.ngroup

df.index = df.groupby(level=0).ngroup()
print (df)
   value
0    1.0
0    2.0
1    3.0
1    NaN
2    5.0
2    6.0
3    NaN
3    NaN
4    8.0
4    9.0

答案 1 :(得分:0)

虽然不是很整洁,但我们可以使用unique并创建地图。

<!DOCTYPE html>

<body>
  <div class="background">
    <div class="bg">
      <img src="https://i.imgur.com/gsceMM5.png" class="banner">
      <ul>
        <li><a class="active" href="index.html">Home</a></li>
        <li><a href="stats.html">Stats</a></li>
        <li><a href="history.html">History</a></li>
        <li><a href="info.html">Info</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
      <p class="header"> WELCOME</p>
      <hr class="dotted_line" />
      <p class="sub_header">What is Bitcoin?</p>
      <video class="video" poster="images/thumbnail.jpg" controls>
        <source src="videos/info.mp4" type="video/mp4">
      </video>
      <p class="credit">
        (Credit to <a class="credit_link" href="https://www.youtube.com/user/weusecoins">WeUseCoins</a> on youtube.com)
      </p>
      <div class="format">
        <img src="https://i.imgur.com/BGsKZms.png" id="image" />
        <p id="text">
          Bitcoin is a new currency that was created in 2009 by an unknown person using the alias Satoshi Nakamoto. Transactions are made with no middle men – meaning, no banks! Bitcoin can be used to book hotels on Expedia, shop for furniture on Overstock and
          buy Xbox games. But much of the hype is about getting rich by trading it. The price of bitcoin skyrocketed into the thousands in 2017.
        </p>
      </div>
    </div>
  </div>
</body>