转换Pandas Dataframe

时间:2013-12-12 14:02:23

标签: python pandas dataframe

是否有一个pandas函数来转换这些数据,因此它将列显示为a,b,c,d,e或数据字段中的任何内容,并且行计算有多少字母。

import pandas as pd

trans = pd.read_table('output.txt', header=None, index_col=0)

print trans
>>> 
        1  2    3    4
0                     
11      a  b    c  NaN
666     a  d    e  NaN
10101   b  c    d  NaN
1010    a  b    c    d
414147  b  c  NaN  NaN
10101   a  b    d  NaN
1242    d  e  NaN  NaN
101     a  b    c    d
411     c  d    e  NaN
444     a  b    c  NaN

相反,我希望输出像这样:

        a  b    c     d   e
0                     
11      1  1    1   NaN  NaN
666     1  NaN  NaN   1    1

函数.stack()几乎完成它但格式错误。

2 个答案:

答案 0 :(得分:5)

您也可以使用Pandas get_dummies()

pd.get_dummies(df.unstack().dropna()).groupby(level=1).sum()

结果:

        a  b  c  d  e
0                    
11      1  1  1  0  0
666     1  0  0  1  1
10101   0  1  1  1  0
1010    1  1  1  1  0
414147  0  1  1  0  0
10101   1  1  0  1  0
1242    0  0  0  1  1
101     1  1  1  1  0
411     0  0  1  1  1
444     1  1  1  0  0

你可以用你想要的NaN替换零。

在一行中有点模糊。 df.unstack().dropna()基本上将您的DataFrame展平为一系列并删除了NaN。 get_dummies给出了所有字母出现的表格,但是对于出栈的DataFrame中的每个级别都是如此。然后,分组和总和将索引与原始形状组合在一起。

答案 1 :(得分:2)

这样的事情可能是:

>>> st = pd.DataFrame(trans.stack()).reset_index(level=0)
>>> st.columns = ['i','c']
>>> st.pivot_table(rows='i', cols='c', aggfunc=len)
c        a   b   c   d   e
i                         
11       1   1   1 NaN NaN
101      1   1   1   1 NaN
411    NaN NaN   1   1   1
444      1   1   1 NaN NaN
666      1 NaN NaN   1   1
1010     1   1   1   1 NaN
1242   NaN NaN NaN   1   1
10101    1   2   1   2 NaN
414147 NaN   1   1 NaN NaN
相关问题