String 基于另一列中的off值将列值连接到新列中
我有一个数据帧,格式如下:String 基于另一列中的off值将列值连接到新列中,string,pandas,dataframe,concatenation,conditional-formatting,String,Pandas,Dataframe,Concatenation,Conditional Formatting,我有一个数据帧,格式如下: Item Balance Date 1 200000 1/1/2020 1 155000 2/1/2020 1 100000 3/1/2020 1 25000 4/1/2020 1 0 5/1/2020 2 100000 1/1/2020 2 15000 2/1/2020 2
Item Balance Date
1 200000 1/1/2020
1 155000 2/1/2020
1 100000 3/1/2020
1 25000 4/1/2020
1 0 5/1/2020
2 100000 1/1/2020
2 15000 2/1/2020
2 0 3/1/2020
Item Cycle
1 4;2#01/01/2020;1000#02/01/2020;775#03/01/2020;500#04/01/2020;125#05/01/2020;0
2 2;2#01/01/2020;1000#02/01/2020;150#03/01/2020;0
我想将数据帧更改为以下格式:
Item Balance Date
1 200000 1/1/2020
1 155000 2/1/2020
1 100000 3/1/2020
1 25000 4/1/2020
1 0 5/1/2020
2 100000 1/1/2020
2 15000 2/1/2020
2 0 3/1/2020
Item Cycle
1 4;2#01/01/2020;1000#02/01/2020;775#03/01/2020;500#04/01/2020;125#05/01/2020;0
2 2;2#01/01/2020;1000#02/01/2020;150#03/01/2020;0
周期列的形式为每个项目的非零值计数(平衡字段)(项目1有4个,项目2有2个),后跟一个;常数为2,后跟a#日期列中的日期,初始缩放值为1000。然后#+(下一个日期值)+(项目当前余额/项目初始余额)*初始比例余额(1000),直到项目观察值达到0的余额。当物料余额为0时;循环变量将以#(日期列中的日期)结束;0还请注意,在周期变量中,日期将采用mm/dd/yyyy的形式
提前感谢您的帮助。假设您的
Date
列已转换为datetime64
:
def summarize(group):
# The number of line items where Balance > 0
count = (group['Balance'] > 0).sum()
# Scale the data where the initial balance = 1000
scaled = pd.DataFrame({
'Balance': group['Balance'] / group['Balance'].iloc[0] * 1000,
'Date': group['Date'].dt.strftime('%m/%d/%Y')
})
# The lambda to produce the string 01/01/2020;1000
f = lambda row: f'{row["Date"]};{row["Balance"]:.0f}'
# Join the balances togather
data = '#'.join(scaled.apply(f, axis=1))
# The final string for each group
return f'{count};2#{data}'
df.groupby('Item').apply(summarize)
请分享你迄今为止所做的尝试。