【问题标题】:Extract elements from a list of lists and assign that as a value in a pandas data frame column从列表列表中提取元素并将其分配为熊猫数据框列中的值
【发布时间】:2016-12-01 21:02:28
【问题描述】:

我有一个生成的列表列表如下:

input = ['a','b','c','d','e','f','g']
siglist = sum([map(list, combinations(input, i)) for i in range(len(input) + 1)], [])

print siglist[25]
    ['d', 'g']

现在,我想在现有数据框 df 中创建一个“新”列,如下所示

color   location    type    new
blue    TX          MATTE   [d,g]
black   NA          GLOSS   [d,g]
red     UT          MATTE   [d,g]
orange  UT          GLOSS   [d,g]
white   WA          MATTE   [d,g]

我希望像下面这样的东西会起作用;

df['new'] = (siglist[25])[:]

但是,我收到一个错误:ValueError: Length of values does not match length of index 任何人都可以帮忙,这里做错了什么。

【问题讨论】:

    标签: list python-2.7 pandas


    【解决方案1】:

    尝试使用apply通过loc分配

    df.loc[:, 'new'] = df.apply(lambda x: (siglist[25])[:], axis=1)
    

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 2021-01-14
      • 2021-01-01
      • 2019-09-30
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多