简体   繁体   中英

Python Dataframe simple average error: TypeError: Expected tuple, got str

I'm executing a very simple operation where I want to change a value in a dataframe to be the average of the preceding values.

period = 14    
u[u.index[period-1]] = np.mean( u[:period] )

However this returns a lengthy error ending with

File "pandas\_libs\lib.pyx", line 2399, in pandas._libs.lib.tuples_to_object_array

TypeError: Expected tuple, got str

I am very much a novice..

thank you very much in advance.

[edit]

Data sample:

Instrument  S&PCOMP
Field   
Dates   
12/05/2015  0
13/05/2015  0
14/05/2015  22.62
15/05/2015  1.63
18/05/2015  6.47
19/05/2015  0
20/05/2015  0
21/05/2015  4.97
22/05/2015  0
25/05/2015  0
26/05/2015  0
27/05/2015  19.28
28/05/2015  0

Expected output:

Instrument  S&PCOMP
Field   
Dates   
12/05/2015  0
13/05/2015  0
14/05/2015  22.62
15/05/2015  1.63
18/05/2015  6.47
19/05/2015  0
20/05/2015  0
21/05/2015  4.97
22/05/2015  0
25/05/2015  0
26/05/2015  0
27/05/2015  19.28
28/05/2015  4.580833333

You can select rows by positions by DataFrame.iloc and then also is used Series.mean method from pandas:

u.iloc[period-1] = u.iloc[:period].mean()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM