Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中基于列的值重复行_Python_Pandas_Numpy - Fatal编程技术网

如何在Python中基于列的值重复行

如何在Python中基于列的值重复行,python,pandas,numpy,Python,Pandas,Numpy,我有以下df,包括代码/产品和周列 code. Product . weeks 123 . product1 . 1;2 123 . product1 . 3 321 . product2 . 4;5;6 321 . product2 . 7 对于那些超过1周的行(例如1;2或4;5;6),我想重复这些行。我期望的结果如下: code. Product . weeks 123 . product1 . 1 123 . product1

我有以下df,包括代码/产品和周列

code.  Product  .   weeks
123 .  product1 .    1;2
123 .  product1 .    3
321 .  product2 .    4;5;6
321 .  product2 .    7
对于那些超过1周的行(例如1;2或4;5;6),我想重复这些行。我期望的结果如下:

code.  Product  .   weeks
123 .  product1 .    1
123 .  product1 .    2
123 .  product1 .    3
321 .  product2 .    4
321 .  product2 .    5
321 .  product2 .    6
321 .  product2 .    7
使用熊猫或numpy的最佳方法是什么

使用:

df = (df.set_index(['code','Product'])['weeks']
       .str.split(';', expand=True)
       .stack()
       .reset_index(level=2, drop=True)
       .reset_index(name='weeks'))
print (df)
   code   Product weeks
0   123  product1     1
1   123  product1     2
2   123  product1     3
3   321  product2     4
4   321  product2     5
5   321  product2     6
6   321  product2     7
说明

  • 首先是所有重复的列
  • 创建
    DataFrame
    by
  • 重塑
  • 上次数据清理由
  • 另一个解决方案:

    from itertools import chain
    
    weeks = df['weeks'].str.split(';')
    lens = weeks.str.len()
    df = pd.DataFrame({
        'code' : df['code'].repeat(lens),
        'Product' : df['Product'].repeat(lens),
        'weeks' : list(chain.from_iterable(weeks.values.tolist())), 
    })
    
    print (df)
       code   Product weeks
    0   123  product1     1
    0   123  product1     2
    1   123  product1     3
    2   321  product2     4
    2   321  product2     5
    2   321  product2     6
    3   321  product2     7
    
    说明

  • 按创建列表
  • 通过以下方式获取LSIT的长度:
  • 最后一列和展平
    weeks

  • 第一个解决方案的可能副本似乎工作正常,除了在my df中,它排除了['weeks']列值中没有(“;”)的行。与上述原始df相关,第3周和第7周的数据未出现。我认为这与str.split函数意外排除附加数据有关。您帮助查找最后一段丢失的代码将非常有帮助@jwlon81-那么第一个解决方案失败,第二个工作?如果数据不保密,是否可以将csv发送到我个人资料中的电子邮件进行测试?嗨,Jezrael,我不确定发生了什么,但我再次运行了代码,我现在可以工作了!谢谢
    #assume test.xlsx is your data
    test = pd.read_excel('test.xlsx')  
    test_processed = pd.DataFrame(columns=test.columns)
    for index, row in test.iterrows():
       weeks = row['weeks'].split(';')
       for week in weeks:
           test_processed = test_processed.append({'code':row['code'], 'Product':row['Product'],'weeks':week}, ignore_index=True)