将列名称分配给pandas系列 [英] assigning column names to a pandas series

查看:51
本文介绍了将列名称分配给pandas系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有熊猫系列

object x
Ezh2   2
Hmgb   7
Irf1   1

我想将此保存为分别具有列名称Gene和Count的数据框 我尝试过

I want to save this as a dataframe with column names Gene and Count respectively I tried

x_df = pd.DataFrame(x,columns = ['Gene','count'])

但是它不起作用.我想要的最终形式是

but it does not work.The final form I want is

Gene Count
Ezh2   2
Hmgb   7
Irf1   1

你能建议怎么做

推荐答案

您可以创建一个dict并将其作为数据参数传递给dataframe构造函数:

You can create a dict and pass this as the data param to the dataframe constructor:

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

或者您可以从系列中创建df,您需要调用reset_index,因为将使用索引,然后重命名列:

Alternatively you can create a df from the series, you need to call reset_index as the index will be used and then rename the columns:

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

这篇关于将列名称分配给pandas系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆