在添加数据时从数据框中删除列表

时间:2018-09-19 21:48:32

标签: python pandas dataframe

以:

开头
import pandas as pd

lis1= [['apples'],['bananas','oranges','cinnamon'],['pears','juice']]
lis2= [['john'],['stacy'],['ron']]

pd.DataFrame({'fruits':lis1,'users':lis2})

                         fruits    users
0                      [apples]   [john]
1  [bananas, oranges, cinnamon]  [stacy]
2                [pears, juice]    [ron]

我想结尾为:

lis3= ['apples','bananas','oranges','cinnamon','pears','juice']
lis4= ['john','stacy','stacy','stacy','ron','ron']

pd.DataFrame({'fruits': lis3, 'users':lis4})

     fruits  users
0    apples   john
1   bananas  stacy
2   oranges  stacy
3  cinnamon  stacy
4     pears    ron
5     juice    ron

首先,我需要创建一个新的数据框,其中每个项目都位于其自己的行中。其次,名称变量需要根据“水果”的数量重复其自身。因此,在示例中,John拥有一个水果,而Stacy有5个水果-因此在用户名下,Stacy必须重复5次。

3 个答案:

答案 0 :(得分:3)

itertools

from itertools import chain, product, starmap

pd.DataFrame(
    [*chain(*starmap(product, zip(df.fruits, df.users)))],
    columns=df.columns
)

     fruits  users
0    apples   john
1   bananas  stacy
2   oranges  stacy
3  cinnamon  stacy
4     pears    ron
5     juice    ron

如果您只有2列,这也可以使用

pd.DataFrame(
    [*chain(*starmap(product, zip(*map(df.get, df))))],
    columns=df.columns
)

generator

def f(z):
  for A, B in z:
    for a in A:
      for b in B:
        yield (a, b)

pd.DataFrame([*f(zip(df.fruits, df.users))], columns=df.columns)

     fruits  users
0    apples   john
1   bananas  stacy
2   oranges  stacy
3  cinnamon  stacy
4     pears    ron
5     juice    ron

答案 1 :(得分:2)

假设lis1lis2具有相同数量的元素,则可以在压缩列表后通过列表理解来做到这一点。

pd.DataFrame(
  [{'fruit':F, 'users':U} for (f, u) in zip(lis1, lis2) for F in f for U in u]
)

以下代码产生以下输出:

      fruit    users
0    apples     john
1   bananas    stacy
2   oranges    stacy
3  cinnamon    stacy
4     pears      ron
5     juice      ron

答案 2 :(得分:1)

这是一个具有大量堆叠和卸载功能的解决方案:

开始于:

>>> df
                         fruits    users
0                      [apples]   [john]
1  [bananas, oranges, cinnamon]  [stacy]
2                [pears, juice]    [ron]

使用:

final = (df.stack().apply(pd.Series)
         .stack(0).unstack(1)
         .ffill()
         .reset_index(drop=True))

>>> final
     fruits  users
0    apples   john
1   bananas  stacy
2   oranges  stacy
3  cinnamon  stacy
4     pears    ron
5     juice    ron