Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas set_Value with DatetimeIndex [Python]

I'm trying to add the row-wise result from a function into my dataframe using df.set_Value.

df in the format :

    Count   DTW
DateTime        
2015-01-16  10  0
2015-01-17  28  0

Using df.setValue

dw.set_Value(idx, 'col', dtw) # idx and dtw are int values

TypeError: cannot insert DatetimeIndex with incompatible label

How do I solve this error or what alternative method with comparable efficiency is there?

like image 650
SerialDev Avatar asked Aug 19 '16 13:08

SerialDev


People also ask

What is DatetimeIndex pandas?

DatetimeIndex [source] Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata such as frequency information.

How do I merge two indexes in pandas?

You can use pandas. merge() to merge DataFrames by matching their index. When merging two DataFrames on the index, the value of left_index and right_index parameters of merge() function should be True . and by default, the pd.

How do I assign a value to a row in pandas?

Example #1: Use set_value() function to set the value in the dataframe at a particular index.


1 Answers

I think you have Series, not DataFrame, so use Series.set_value with index converted to datetime

dw = pd.Series([-2374], index = [pd.to_datetime('2015-01-18')])
dw.index.name = 'DateTime'
print (dw)
DateTime
2015-01-18   -2374
dtype: int64

print (dw.set_value(pd.to_datetime('2015-01-19'), 1))
DateTime
2015-01-18   -2374
2015-01-19       1
dtype: int64

print (dw.set_value(pd.datetime(2015, 1, 19), 1))
DateTime
2015-01-18   -2374
2015-01-19       1
dtype: int64

More standard way is use ix or iloc:

print (dw)
            Count  DTW
DateTime              
2015-01-16     10    0
2015-01-17     28    0

dw.ix[1, 'DTW'] = 10
#dw.DTW.iloc[1] = 10
print (dw)
            Count  DTW
DateTime              
2015-01-16     10    0
2015-01-17     28   10
like image 152
jezrael Avatar answered Sep 23 '22 20:09

jezrael