【问题标题】:Turning column values into Integer columns - Pandas将列值转换为整数列 - Pandas
【发布时间】:2017-10-09 07:16:40
【问题描述】:

给定一系列未知大小的内部列表:

import pandas as pd
sr = pd.Series([['a', 'b', 'c', 'b'], ['a', 'a', 'd'], ['b']])

[出]:

0    [a, b, c, b]
1       [a, a, d]
2             [b]

目标是使用内部列表中的值来创建列并使用每行中的项目数填充其值,即

     a    b    c    d
0  1.0  2.0  1.0  NaN
1  2.0  NaN  NaN  1.0
2  NaN  1.0  NaN  NaN

我尝试通过遍历每一行并将它们转换为 Counter 对象并使用计数器字典列表重新创建数据框来实现上述目的:

>>> from collections import Counter
>>> pd.DataFrame([dict(Counter(row)) for row in pd.Series([['a', 'b', 'c', 'b'], ['a', 'a', 'd'], ['b']])])

有没有更简单的方法来做到这一点?也许用.pivot()

【问题讨论】:

    标签: python pandas counter series nested-lists


    【解决方案1】:

    我认为如果输入是 list 就像上一个问题一样:

    lol = [['a', 'b', 'c', 'b'], ['a', 'a', 'd'], ['b']]
    df = pd.DataFrame(Counter(x) for x in lol)
    print (df)
         a    b    c    d
    0  1.0  2.0  1.0  NaN
    1  2.0  NaN  NaN  1.0
    2  NaN  1.0  NaN  NaN
    

    如果输入是Series:

    df = pd.DataFrame(sr.values.tolist()).apply(pd.value_counts, 1)
    print (df)
         a    b    c    d
    0  1.0  2.0  1.0  NaN
    1  2.0  NaN  NaN  1.0
    2  NaN  1.0  NaN  NaN
    

    【讨论】:

      【解决方案2】:

      使用

      In [179]: pd.DataFrame(Counter(x) for x in sr)
      Out[179]:
           a    b    c    d
      0  1.0  2.0  1.0  NaN
      1  2.0  NaN  NaN  1.0
      2  NaN  1.0  NaN  NaN
      

      或者

      In [182]: sr.apply(lambda x: pd.Series(Counter(x)))
      Out[182]:
           a    b    c    d
      0  1.0  2.0  1.0  NaN
      1  2.0  NaN  NaN  1.0
      2  NaN  1.0  NaN  NaN
      

      value_counts

      In [170]: sr.apply(lambda x: pd.Series(x).value_counts())
      Out[170]:
           a    b    c    d
      0  1.0  2.0  1.0  NaN
      1  2.0  NaN  NaN  1.0
      2  NaN  1.0  NaN  NaN
      

      或者

      In [174]: pd.DataFrame(pd.Series(x).value_counts() for x in sr)
      Out[174]:
           a    b    c    d
      0  1.0  2.0  1.0  NaN
      1  2.0  NaN  NaN  1.0
      2  NaN  1.0  NaN  NaN
      

      【讨论】:

        猜你喜欢
        • 2021-10-13
        • 1970-01-01
        • 2019-08-04
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多