Bosco Tsin
Bosco Tsin

Reputation: 183

Cannot Get Series From Dataframe (Python)

a = np.random.standard_normal((9,4))
dg = pd.DataFrame(a)
dg.columns = [["No1", "No2", "No3", "No4"]]
dg["No1"]

Hello all. I have been using JupyterLab opened through Anaconda Navigator and I wrote the above code. The first three lines look normal, however, for the fourth line I was given an error as below. If I change the fourth line into dg[["No1"]] then it "worked". However, in that case type(dg[["No1"]]) is actually dataframe, not series.

I am a bit noob and I have scratched my head for almost two hours and still don't understand what's wrong. Can somebody help? Thanks!!!


TypeError                                 Traceback (most recent call last)
<ipython-input-393-b26f43cf53bf> in <module>
----> 1 dg["No1"]

~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2774                 if self.columns.nlevels > 1:
   2775                     return self._getitem_multilevel(key)
-> 2776                 return self._get_item_cache(key)
   2777 
   2778         # Do we have a slicer (on rows)?

~\anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
   3584         res = cache.get(item)
   3585         if res is None:
-> 3586             values = self._data.get(item)
   3587             res = self._box_item_values(item, values)
   3588             cache[item] = res

~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in get(self, item)
    966                         raise ValueError("cannot label index with a null key")
    967 
--> 968             return self.iget(loc)
    969         else:
    970 

~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in iget(self, i)
    983         Otherwise return as a ndarray
    984         """
--> 985         block = self.blocks[self._blknos[i]]
    986         values = block.iget(self._blklocs[i])
    987 

TypeError: only integer scalar arrays can be converted to a scalar index

Upvotes: 0

Views: 217

Answers (1)

NYC Coder
NYC Coder

Reputation: 7604

You can just do this, unless you want multi-index :

dg.columns = ["No1", "No2", "No3", "No4"]

Upvotes: 2

Related Questions