如何将Series索引转换为两列作为DataFrame

时间:2016-05-18 04:28:39

标签: python pandas

我有以下熊猫系列:

import pandas as pd
import io
from scipy import stats

test=u"""probegenes,sample1
1415777_at Pnliprp1,20
1415884_at Cela3b,47
1415805_at Clps,17
1115805_at Ckkk,77
"""
df_test = pd.read_csv(io.StringIO(test),index_col='probegenes')
my_series = df_test['sample1']
my_series

看起来像这样:

In [62]: my_series
Out[62]:
probegenes
1415777_at Pnliprp1    20
1415884_at Cela3b      47
1415805_at Clps        17
1115805_at Ckkk        77
Name: sample1, dtype: int64

我想要做的是分裂探测基因'索引,以便我获得新的数据框:

  Probe      Genes      Score
0 1415777_at Pnliprp1    20
1 1415884_at Cela3b      47
2 1415805_at Clps        17
3 1115805_at Ckkk        77

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

转换为.str.split(expand=True)index可以Series.concat()可以column结果:

df = pd.concat([my_series,my_series.index.to_series().str.split(expand=True)], axis=1).reset_index(drop=True)
df.rename(columns={'sample1': 'Score', 0: 'probe', 1: 'genes'})

的产率:

     Score       Probe     Genes
0       20  1415777_at  Pnliprp1
1       47  1415884_at    Cela3b
2       17  1415805_at      Clps
3       77  1115805_at      Ckkk

答案 1 :(得分:2)

df = pd.DataFrame([i.split(" ") for i in my_series.index], columns=['Probe', 'Genes'])
df['Score'] = my_series.values

>>> df
        Probe     Genes  Score
0  1415777_at  Pnliprp1     20
1  1415884_at    Cela3b     47
2  1415805_at      Clps     17
3  1115805_at      Ckkk     77
相关问题