Python 如何将系列索引转换为两列作为数据帧
我有以下熊猫系列:Python 如何将系列索引转换为两列作为数据帧,python,pandas,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_seri
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
如何实现这一点?在转换到系列后,您可以在索引上.str.split(expand=True)
和.concat()
第一列的结果:
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
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