将Pandas数据框中的值拆分为值,并为新值创建行

问题描述 投票:0回答:1

我正在尝试按来源分割计费行的数量。计费行数据量报告为一个值,但我知道55%的卷来自源A,45%来自源B.如何在Pandas数据帧中创建新行以将行拆分为两行,每个来源一个?

我可以计算每个源的新卷值并将其放在新列中,但我不确定如何将这些值输入到新行中。

来源A应为计数的55%,而来源B应为计数的45%。

from pandas import DataFrame
import numpy as np

before = DataFrame([{'Day': 1, 'Billing Line': 'abcdefg', 'Count': 1000},
                   {'Day': 2, 'Billing Line': 'abcdefg', 'Count': 2000}])


after = DataFrame([{'Day': 1, 'Billing Line': 'abcdefg', 'Count': 550, 'Source': 'a'},
               {'Day': 1,'Billing Line': 'abcdefg', 'Count': 450, 'Source':'b'},
                 {'Day': 2,'Billing Line': 'abcdefg', 'Count': 1100, 'Source':'a'},
                  {'Day': 2,'Billing Line': 'abcdefg', 'Count': 900, 'Source':'b'}])
python-3.x pandas
1个回答
0
投票

我们使用unnest

before['pct']=[[0.45,0.55]]*len(before)
before['Source']=[['a','b']]*len(before)

unnesting(before,['pct','Source']).eval('Count=Count*pct')
Out[395]: 
    pct Source Billing Line   Count  Day
0  0.45      a      abcdefg   450.0    1
0  0.55      b      abcdefg   550.0    1
1  0.45      a      abcdefg   900.0    2
1  0.55      b      abcdefg  1100.0    2
© www.soinside.com 2019 - 2024. All rights reserved.