Pandas version 0.16.0 after changing the dataframe index all values ​​become NaN

I am using an ipython laptop and the following pandas examples of cookbook version 0.16.0. I have problems when I am on page 237. I created such a data file

from pandas import *
data1=DataFrame({'AAA':[4,5,6,7],'BBB':[10,20,30,40],'CCC':[100,50,-30,-50]})

then I did this while trying to change the index:

df=DataFrame(data=data1,index=(['a','b','c','d']))

but I get a dataframe with all NaN values! Does anyone know why and how to fix this? I also tried using the set_index function and this gave me errors.

Many thanks! enter image description here

+4
source share
3 answers

If you want to change the index, use either reindexor assign directly to the index:

In [5]:

data1=pd.DataFrame({'AAA':[4,5,6,7],'BBB':[10,20,30,40],'CCC':[100,50,-30,-50]})
print(data1)
df=pd.DataFrame(data=data1)
df.index = ['a','b','c','d']
df
   AAA  BBB  CCC
0    4   10  100
1    5   20   50
2    6   30  -30
3    7   40  -50
Out[5]:
   AAA  BBB  CCC
a    4   10  100
b    5   20   50
c    6   30  -30
d    7   40  -50

, , , :

In [7]:

df=pd.DataFrame(data=data1.values,index=(['a','b','c','d']))
df
Out[7]:
   0   1    2
a  4  10  100
b  5  20   50
c  6  30  -30
d  7  40  -50

, , df, df

, df, , :

In [46]:

data1 = pd.DataFrame({'AAA':[4,5,6,7],'BBB':[10,20,30,40],'CCC':[100,50,-30,-50]})
data1.reindex_axis(list('abcd'))
Out[46]:
   AAA  BBB  CCC
a  NaN  NaN  NaN
b  NaN  NaN  NaN
c  NaN  NaN  NaN
d  NaN  NaN  NaN

, df, , BlockManager df:

, , frame.py:

        if isinstance(data, BlockManager):
        mgr = self._init_mgr(data, axes=dict(index=index, columns=columns),
                             dtype=dtype, copy=copy)

generic.py:

119         def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
120             """ passed a manager and a axes dict """
121             for a, axe in axes.items():
122                 if axe is not None:
123                     mgr = mgr.reindex_axis(
124  ->                     axe, axis=self._get_block_manager_axis(a), copy=False)

issue

, , , df, @Jeff

, / .

.

+3

EdChum reindex, , , DataFrame , DataFrame DataFrame.

, , DataFrame ( , DataFrame). , data1.values. , :

In [1]: pd.DataFrame(data=data1.values,columns=data1.columns,index=(['a','b','c','d']))

Out[1]: 
   AAA  BBB  CCC
a    4   10  100
b    5   20   50
c    6   30  -30
d    7   40  -50
+2

set_index, .

Why did this happen? set_indexDesigned to use one or more existing columns to set the index. Thus, it data1.set_index('a')will give Key Error, since ait is not a column in data1, while it data1.set_index['AAA']will give

     BBB  CCC
AAA          
4     10  100
5     20   50
6     30  -30
7     40  -50

The other two answers answer the rest of Q.

+1
source

All Articles