为熊猫行中的逗号分隔的字符串生成组合

时间:2018-12-20 06:53:54

标签: python pandas

我有一个这样的数据框:

ID, Values
1   10, 11, 12, 13
2   14
3   15, 16, 17, 18

我想像这样创建一个新的数据框:

ID COl1 Col2
1  10   11
1  11   12
1  12   13
2  14
3  15   16
3  16   17
3  17   18

请帮助我如何执行此操作??? 注意:输入df的“值”列中的行为str类型。

2 个答案:

答案 0 :(得分:1)

将列表理解与平坦化和较小的更改结合使用-将if i > 0:更改为if i == 2:,以正确使用一个元素值:

from collections import deque

#https://stackoverflow.com/a/36586925
def chunks(iterable, chunk_size=2, overlap=1):
    # we'll use a deque to hold the values because it automatically
    # discards any extraneous elements if it grows too large
    if chunk_size < 1:
        raise Exception("chunk size too small")
    if overlap >= chunk_size:
        raise Exception("overlap too large")
    queue = deque(maxlen=chunk_size)
    it = iter(iterable)
    i = 0
    try:
        # start by filling the queue with the first group
        for i in range(chunk_size):
            queue.append(next(it))
        while True:
            yield tuple(queue)
            # after yielding a chunk, get enough elements for the next chunk
            for i in range(chunk_size - overlap):
                queue.append(next(it))
    except StopIteration:
        # if the iterator is exhausted, yield any remaining elements
        i += overlap
        if i == 2:
            yield tuple(queue)[-i:]

L = [[x] + list(z) for x, y in zip(df['ID'], df['Values']) for z in (chunks(y.split(', ')))]

df = pd.DataFrame(L, columns=['ID','Col1','Col2']).fillna('')
print (df)
   ID Col1 Col2
0   1   10   11
1   1   11   12
2   1   12   13
3   2   14     
4   3   15   16
5   3   16   17
6   3   17   18

答案 1 :(得分:0)

尝试了稍微不同的方法。创建了一个函数,该函数将从初始逗号分隔的字符串中成对返回数字。

def pairup(mystring):
    """Function to return paired up list from string"""
    mylist = mystring.split(',')
    if len(mylist) == 1: return [mylist]
    splitlist = []
    for index, item in enumerate(mylist):
        try:
            splitlist.append([mylist[index], mylist[index+1]])
        except:
            pass
    return splitlist

现在让我们创建一个新的数据框。

# https://stackoverflow.com/a/39955283/3679377
new_df = df[['ID']].join(
    df.Values.apply(lambda x: pd.Series(pairup(x)))
      .stack()
      .apply(lambda x: pd.Series(x))
      .fillna("")
      .reset_index(level=1, drop=True), 
    how='left').reset_index(drop=True)
new_df.columns = ['ID', 'Col 1', 'Col 2']

这是print(new_df)的输出。

   ID Col 1 Col 2
0   1    10    11
1   1    11    12
2   1    12    13
3   2    14      
4   3    15    16
5   3    16    17
6   3    17    18