Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert new row in pandas data frame at desired index

Tags:

I have a data frame which has missing dates

print data 

Date  Longitude  Latitude  Elevation  Max Temperature  \
4/11/1979  83.75  24.197701       238     44.769           20.007   
4/12/1979  83.75  24.197701       238     41.967           18.027   
4/13/1979  83.75  24.197701       238     43.053           20.549    
4/15/1979  83.75  24.197701       238     40.826           20.189

How do I insert 4/14/1979 at the 4th row

print data

Date  Longitude  Latitude  Elevation  Max Temperature  \
4/11/1979  83.75  24.197701       238     44.769           20.007   
4/12/1979  83.75  24.197701       238     41.967           18.027   
4/13/1979  83.75  24.197701       238     43.053           20.549
4/14/1979  0.0    0.0             0       0.0              0.0
4/15/1979  83.75  24.197701       238     40.826           20.189
like image 505
Gurminder Bharani Avatar asked Sep 19 '16 18:09

Gurminder Bharani


People also ask

How do I add a row to a Dataframe at a specific index?

concat() function to insert a row at any given position in the dataframe.

How do I manually add a row to a Pandas Dataframe?

The easiest way to add or insert a new row into a Pandas DataFrame is to use the Pandas . append() method. The . append() method is a helper method, for the Pandas concat() function.

How do I add a row in iLOC?

You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement.

How do I change the index of a row in pandas?

To change the index values we need to use the set_index method which is available in pandas allows specifying the indexes.


1 Answers

First convert column Date to_datetime, then set_index for resampling.

You can use resample by D (days) and then need fill NaN to 0, one posible solution is replace({np.nan:0}):

df['Date'] = pd.to_datetime(df.Date)
df.set_index('Date', inplace=True)

df = df.resample('D').replace({np.nan:0}).reset_index()
print (df)
        Date  Longitude   Latitude  Elevation     Max  Temperature
0 1979-04-11      83.75  24.197701      238.0  44.769       20.007
1 1979-04-12      83.75  24.197701      238.0  41.967       18.027
2 1979-04-13      83.75  24.197701      238.0  43.053       20.549
3 1979-04-14       0.00   0.000000        0.0   0.000        0.000
4 1979-04-15      83.75  24.197701      238.0  40.826       20.189
like image 169
jezrael Avatar answered Sep 25 '22 16:09

jezrael