Pandas smoothed hierarchical index on nonoverlapping columns

I have a dataframe and I set the index to the column of the data frame. This creates a hierarchical column index. I want to smooth the columns one level. Like this question - Python Pandas - how to flatten the hierarchical index in columns , however the columns do not overlap (ie, the "id" is not at level 0 of the hierarchical index, and the other columns are at level 1 of the index).

df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
df.set_index('id', inplace=True)

      A    B
id
101   3    x
102   5    y

The desired output is flattened columns, for example:

id    A    B
101   3    x
102   5    y
+4
source share
3 answers

You misinterpret what you see.

     A  B
id       
101  3  x
102  5  y

. id - . , pandas .

, .

df, csv , :

print(df.to_csv(sep='\t'))

id  A   B
101 3   x
102 5   y

print(df.to_csv())

id,A,B
101,3,x
102,5,y

df , ,

print(df.rename_axis(None)) 

     A  B
101  3  x
102  5  y

, !!!!
, ,

, , .

print(df.rename_axis(None).rename_axis('id', 1))

id   A  B
101  3  x
102  5  y

id, .

+1

. "id" , , , pandas , 0.

df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])

In[52]: df
Out[52]: 
    id  A  B
0  101  3  x
1  102  5  y

, . ,

df.iloc[0]
Out[53]: 
id    101
A       3
B       x
Name: 0, dtype: object

, , ID , , :

df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
df.set_index('id', inplace=True)
df['id'] = df.index
df
Out[55]: 
     A  B   id
id            
101  3  x  101
102  5  y  102

"id", :

df.loc[101]
Out[57]: 
A       3
B       x
id    101
Name: 101, dtype: object

​​ :

df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
df.set_index('id', inplace=True)
df.loc[101]

Out[58]: 
A    3
B    x
Name: 101, dtype: object
+1

:

>>> df2=pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B'])
>>> df2.set_index('id', inplace=True)
>>> df2
     A  B
id       
101  3  x
102  5  y

purdy DataFrame reset .to_string:

>>> print df2.reset_index().to_string(index=False)
id  A  B
101  3  x
102  5  y

, :

>>> fmts=[lambda s: u"{:^5}".format(str(s).strip())]*3
>>> print df2.reset_index().to_string(index=False, formatters=fmts)
id     A      B
101    3      x  
102    5      y
+1

Source: https://habr.com/ru/post/1657877/


All Articles