TypeError与Dataframe:list indices必须是整数或切片,而不是str

时间:2017-03-12 10:55:24

标签: dataframe types

我正在通过以下示例并继续收到错误:

import pandas as pd
import quandl

df = quandl.get('WIKI/GOOGL')
df = [['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']]
print(df.head())

TypeError:list indices必须是整数或切片,而不是str

2 个答案:

答案 0 :(得分:1)

你用vanilla Python列表覆盖了你的DF:

df = [['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']]

试试这个:

In [102]: df = df.filter(regex='^Adj\.')

In [103]: df
Out[103]:
             Adj. Open   Adj. High    Adj. Low  Adj. Close  Adj. Volume
Date
2004-08-19   50.159839   52.191109   48.128568   50.322842   44659000.0
2004-08-20   50.661387   54.708881   50.405597   54.322689   22834300.0
2004-08-23   55.551482   56.915693   54.693835   54.869377   18256100.0
2004-08-24   55.792225   55.972783   51.945350   52.597363   15247300.0
2004-08-25   52.542193   54.167209   52.100830   53.164113    9188600.0
2004-08-26   52.637487   54.142132   52.492038   54.122070    7094800.0
2004-08-27   54.217364   54.478169   53.008633   53.239345    6211700.0
...                ...         ...         ...         ...          ...
2017-03-02  856.310000  856.490000  848.720000  849.850000    1243221.0
2017-03-03  848.940000  850.820000  844.705000  849.080000     999655.0
2017-03-06  846.860000  848.940000  841.170000  847.270000    1030586.0
2017-03-07  847.260000  853.330000  845.520000  851.150000    1018514.0
2017-03-08  853.120000  856.930000  851.250000  853.640000    1019962.0
2017-03-09  853.690000  860.710000  852.670000  857.840000    1322603.0
2017-03-10  862.700000  864.229000  857.610000  861.405000    1326432.0

[3162 rows x 5 columns]

答案 1 :(得分:1)

我认为您忘了在重新确定df时在双括号之前输入df。应该是:df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']]