przypisywanie nazw kolumn serii pandy

Mam serię pand

object x
Ezh2   2
Hmgb   7
Irf1   1

Chcę zapisać to jako dataframe z nazwami kolumn odpowiednio Gene I Count Próbowałem

x_df = pd.DataFrame(x,columns = ['Gene','count'])
Ale to nie działa.Ostateczna forma jaką chcę to
Gene Count
Ezh2   2
Hmgb   7
Irf1   1

Czy możesz zasugerować, Jak to zrobić

Author: jpp, 2015-02-13

3 answers

Możesz utworzyć dict i przekazać to jako param danych do konstruktora dataframe:

In [235]:

df = pd.DataFrame({'Gene':s.index, 'count':s.values})
df
Out[235]:
   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

Alternatywnie możesz utworzyć df z serii, musisz wywołać {[2] } ponieważ indeks zostanie użyty, a następnie zmienić nazwę kolumn:

In [237]:

df = pd.DataFrame(s).reset_index()
df.columns = ['Gene', 'count']
df
Out[237]:
   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1
 43
Author: EdChum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-13 15:59:24

Można również użyć metody .to_frame().

Jeśli jest to szereg, zakładam ,że 'Gen' jest już indeksem i pozostanie indeksem po przekształceniu go w ramkę danych. Argument name z .to_frame() wywoła nazwę kolumny.

x = x.to_frame('count')

Jeśli chcesz je obie jako kolumny, możesz zresetować indeks:

x = x.to_frame('count').reset_index()
 31
Author: Sealander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-29 18:26:18

Jeśli masz pd.Series obiekt x o indeksie o nazwie 'Gene', możesz użyć reset_index i podać name argument:

df = x.reset_index(name='count')

Oto demo:

x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'

df = x.reset_index(name='count')

print(df)

   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1
 6
Author: jpp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-30 11:18:24