1

I have a pandas series object consists of a datetime_index and some values, looks like following:

df
2020-01-01 00:00:00    39.6
2020-01-01 00:15:00    35.6
2020-01-01 00:30:00    35.6
2020-01-01 00:45:00    39.2
2020-01-01 01:00:00    56.7
...
2020-12-31 23:45:00    56.3

I am adding some values to this df with .append(). Since it is not sorted then I sort its index via .sort_index(). However what I would like to achieve is that I want to sort only for given day.

So for example I add some values to day 2020-01-01, and since the added values will be after the end of the day 2020-01-01 I just need to sort the first day of the year. NOT ALL THE DF.

Here is an example, NaN value is added with .append():

df
2020-01-01 00:00:00    39.6
2020-01-01 00:15:00    35.6
...
2020-01-01 23:45:00    34.3
2020-01-01 15:00:00    NaN
...
2020-12-31 23:45:00    56.3

Now I cannot df.sort_index(), because it breaks other days. That is why I just want to apply .sort_index() to the day 2020-01-01. How do I do that?

WHAT I TRIED SO FAR AND DOES NOT WORK:

df.loc['2020-01-01'] = df.loc['2020-01-01'].sort_index()

1 Answer 1

1

Filter rows for 2020-01-01 days, sorting and join back with not matched rows:

mask = df.index.normalize() == '2020-01-01'

df = pd.concat([df[mask].sort_index(), df[~mask]])
print (df)
2020-01-01 00:00:00    39.6
2020-01-01 00:15:00    35.6
2020-01-01 15:00:00     NaN
2020-01-01 23:45:00    34.3
2020-12-31 23:45:00    56.3
Name: a, dtype: float64

Another idea:

df1 = df['2020-01-01'].sort_index()
df = pd.concat([df1, df.drop(df1.index)])
4
  • First one works, I can try also the second one. Can I ask you what does ~ before mask do? @jezrael thank you!!!
    – oakca
    Feb 12, 2021 at 11:51
  • @oakca - It change [False, True, True] to [True, False, False], working like mask == False
    – jezrael
    Feb 12, 2021 at 11:52
  • both of them works. So ~ is like an inverter, however I am not sure what is [False, True, True] stands for. Anyway
    – oakca
    Feb 12, 2021 at 11:56
  • @oakca - I want explain like working inverting mask ;)
    – jezrael
    Feb 12, 2021 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.