使用Python / Pandas为特定列值添加/复制行



当特定列具有特定值时,我正在尝试使用 pandas 数据框将新/重复的行插入到 excel 中。如果列值为 TRUE,则复制该行并更改其值。

例如:

Input
A        B      C   D   
0   Red      111    A   2   
1   Blue     222    B   12  
2   Green    333    B   3
3   Black    111    A   2   
4   Yellow   222    D   12  
5   Pink     333    c   3
6   Purple   777    B   10
Output
A        B      C   D   
0   Red      111    A   2   
1   Blue     222    Y   12  
2   Blue     222    Z   12
3   Green    333    Y   3
4   Green    333    Z   3
5   Black    111    A   2   
6   Yellow   222    D   12  
7   Pink     333    c   3
8   Purple   777    Y   10
9   Purple   666    Z   10

如果您在这里看到 C 列,当我遇到特定的 Value = B 时,我只想复制该行。 将其值分别在原始行和重复行中更改为 Y 和 Z。(如果我遇到 B 以外的任何内容,请不要重复。

使用concat替换C列,将过滤的行替换为Z,将0.5添加到索引中以始终正确的sort_index

df1 = df.replace({'C': {'B':'Y'}})
df2 = df[df['C'].eq('B')].assign(C = 'Z').rename(lambda x: x + .5)
df = pd.concat([df1, df2]).sort_index().reset_index(drop=True)
print (df)
A    B  C   D
0     Red  111  A   2
1    Blue  222  Y  12
2    Blue  222  Z  12
3   Green  333  Y   3
4   Green  333  Z   3
5   Black  111  A   2
6  Yellow  222  D  12
7    Pink  333  c   3
8  Purple  777  Y  10
9  Purple  777  Z  10

或者创建 3 个不带B值的小数据帧,筛选并设置值并一起concat

mask = df['C'].eq('B')
df0 = df[~mask]
df1 = df[mask].assign(C = 'Y')
df2 = df[mask].assign(C = 'Z').rename(lambda x: x + .5)
df = pd.concat([df0, df1, df2]).sort_index().reset_index(drop=True)

替代方法。

#Replace B with Y & Z first in column C
df.replace({'C': {'B': 'Y,Z'}}, inplace = True)
#Use "explode" Avaible on pandas 0.25 to split the value into 2 columns
df=df.assign(C=df.C.str.split(",")).explode('C') 

最新更新