python pandas 变换数据框 [英] python pandas transforming dataframe

查看:185
本文介绍了python pandas 变换数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个大熊猫函数来转换这个数据,所以它将列显示为a,b,c,d,e或数据字段中的任何内容,而行数则表示有多少个字母。

Is there a pandas function to transform this data so it show the columns as a,b,c,d,e or whatever is inside the data field and the rows count how many of the letters there are.

from pylab import *
import pandas as pd
import numpy as np

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()几乎完成了错误的格式。

The function .stack() almost gets it done but in the wrong format.

推荐答案

你也可以使用熊猫$ $ c> get_dummies()

You could also use 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替换零。

You could replace the zeros with NaN's in you want to.

它在一行中有点模糊。 df.unstack()。dropna()基本上将您的DataFrame平坦化,并丢弃Na Na。 get_dummies 给出了所有出现的字母的表,但是对于拆包DataFrame中的每个级别。分组和总和然后将索引组合到原始形状。

Its a bit obscure in one line. df.unstack().dropna() basically flattens your DataFrame to a series and drops al NaN's. The get_dummies gives a table of all the occurrences of the letters, but for each level in the unstack DataFrame. The grouping and sum then combine the index to the original shape.

这篇关于python pandas 变换数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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