Skip to content Skip to sidebar Skip to footer

How Can I Insert A Row Into A Dataframe, While Preserving Numerical Order Of Row Indexes?

I'm working with a dataframe from a machine that samples every 2 miliseconds, so all my row indexes have been reindexed to the machine's timestamps. There are certain TTL events t

Solution 1:

Add df.sort(inplace=True) after all your additions to the data-frame.

Demo:

import pandas as pd
df = pd.DataFrame({'x': xrange(10), 'y': xrange(10)})
df = df.ix[2::2]  # now we only have "time sample" every 2 ms
df['events'] = ''  # add a TTL channel
df.loc[3, 'events'] = 'kowabunga!'
df.loc[5, 'events'] = 'kowabunga2!'
df.loc[1, 'events'] = 'kowabunga3!'
df.sort(inplace=True)
print df

Output:

    x   y       events
1 NaN NaN  kowabunga3!
2   2   2             
3 NaN NaN   kowabunga!
4   4   4             
5 NaN NaN  kowabunga2!
6   6   6             
8   8   8             

[7 rows x 3 columns]

Post a Comment for "How Can I Insert A Row Into A Dataframe, While Preserving Numerical Order Of Row Indexes?"