“类型”对象不可下标

时间:2018-09-23 05:13:59

标签: python pandas

import pandas as pd
import numpy as np

fruits = ["APPLE","BANANA","GRAPES","ORANGE"]
prices = [80,45,60,50]


fru_prices = pd.DataFrame[fruits,prices]
  

我在创建数据框时遇到错误:“类型”对象为   不可下标

5 个答案:

答案 0 :(得分:1)

pd.DataFrame是一种方法,类型为'type'。因此,您得到的错误为'type' object is not subscriptable。所以,

fru_prices = pd.DataFrame([fruits,prices])

答案 1 :(得分:1)

您必须调用DataFrame,然后将列表作为参数:

fru_prices=pd.DataFrame([fruits,prices])

要转置,请执行以下操作:

fru_prices=fru_prices.T

并且需要这样的列:

fru_prices.columns=['fruits','prices']

然后fru_prices就是您想要的

实际上,您可以单行完成所有操作:

fru_prices=pd.DataFrame([fruits,prices],index=['fruit','prices']).T

相关:

  

请参阅:What does it mean to "call" a function in Python?

答案 2 :(得分:1)

使用以下代码作为:pd.DataFrame是一种方法。 蟒蛇:3.6.2

import pandas as pd
import numpy as np

fruits = ["APPLE","BANANA","GRAPES","ORANGE"]
prices = [80,45,60,50]


fru_prices =pd.DataFrame([fruits,prices])
fru_prices = fru_prices.set_index(0).T ##This entry conver it into row to column
print(fru_prices)

输出:

0   APPLE  80
1  BANANA  45
2  GRAPES  60
3  ORANGE  50

检查此内容,以防此代码起作用。

答案 3 :(得分:0)

    import pandas as pd
    import numpy as np

    fruits = ["APPLE","BANANA","GRAPES","ORANGE"]
    prices = [80,45,60,50]

    fru_prices = list(zip(fruits,prices))

    pd.DataFrame(data = fru_prices ,columns = ['fruits','prices'])

---------------------------------------------------------------------

    output :

    fruits  prices
 0  APPLE   80
 1  BANANA  45
 2  GRAPES  60
 3  ORANGE  50



> Python zip function takes iterable elements as input, and returns
> iterator. Now data will appear in column wise.

答案 4 :(得分:0)

当我使用方括号时,会发生此错误,即“类型”对象不可下标。使用括号可以解决问题。