大熊猫根据其他两列的值复制和编辑“ n”行

时间:2018-10-16 14:20:52

标签: python pandas

考虑以下以下数据框df

from numpy import nan
import pandas as pd
d = {'x': {0: 'MT', 1: 'MT', 2: 'MT', 3: 'MT', 4: 'MT', 3379: 'MT', 3406: 'MT', 4184: 'MT', 4248: 'MT'}, 'Position': {0: 3, 1: 5, 2: 5, 3: 6, 4: 6, 3379: 568, 3406: 573, 4184: 16184, 4248: 16193}, 'Reference': {0: 'T', 1: 'A', 2: 'A', 3: 'C', 4: 'C', 3379: 'C', 3406: 'C', 4184: 'C', 4248: 'C'}, 'Variant': {0: 'C', 1: 'G', 2: 'C', 3: 'T', 4: 'G', 3379: 'C', 3406: 'C', 4184: 'C', 4248: 'C'}, 'Min': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 3379: 2.0, 3406: 2.0, 4184: 2.0, 4248: 2.0}, 'Max': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 3379: 8.0, 3406: 8.0, 4184: 5.0, 4248: 3.0}}

df = pd.DataFrame(d)

我们看到在MinMax列下,我有NaN以及浮点数。最终,我想做的是将Variant下的字母复制n次,而该字母将被复制的数字由MinMax

NaNMin下有Max的地方,在Variant下的观测值应保持不变。

对于在MinMax下有浮点数的每一行,我将对其下的行进行n次复制,其中n等于Max-Min

复制列之后,我将根据VariantMin指定的值在Max下编辑观察值。

例如,考虑到索引3379的行,我将复制此列8-2 = 6次,这样我总共将有7个相同的行。现在,我应该在VariantMinMax的n次下“放大”或隐藏观察对象,这样,考虑到这一行(或索引3379),我的复制将看起来像以下:

d1 = {'x':{3379: 'MT', 3380:'MT', 3381:'MT', 3382:'MT', 3383:'MT', 3384:'MT', 3385:'MT'}, 
      'Position':{3379:568, 3380:568, 3381:568, 3382:568, 3383:568, 3384:568, 3385:568},
      'Reference':{3379:'C', 3380:'C', 3381:'C', 3382:'C', 3383:'C', 3384:'C', 3385:'C'},
      'Variant':{3379:'CC', 3380:'CCC', 3381:'CCCC', 3382:'CCCCC', 3383:'CCCCCC', 3384:'CCCCCCC', 3385:'CCCCCCCC'},
      'Min':{3379:2.0, 3380:2.0, 3381:2.0, 3382:2.0, 3383:2.0, 3384:2.0, 3385:2.0},
      'Max':{3379:8.0, 3380:8.0, 3381:8.0, 3382:8.0, 3383:8.0, 3384:8.0, 3385:8.0}}

df1 = pd.DataFrame(d1)

我想对MinMax下的观察值不为NaNs的所有行执行此操作

1 个答案:

答案 0 :(得分:2)

IIUC,使用默认构造函数和np.repeat

n = (df['Max'] - df['Min'] + 1).fillna(1).astype(int)
df2 = pd.DataFrame({c: df[c].values.repeat(n, axis=0) for c in df.columns}, 
                   index=df.index.repeat(n))

m = df[['Min', 'Max']].notnull().all(1)
df2.loc[m, 'Variant'] = df2.loc[m, 'Variant'] * df2.loc[m].groupby(df2.loc[m].index).cumcount().add(2)

        x       Position   Reference    Variant     Min Max
0       MT      3          T                  C     NaN NaN
1       MT      5          A                  G     NaN NaN
2       MT      5          A                  C     NaN NaN
3       MT      6          C                  T     NaN NaN
4       MT      6          C                  G     NaN NaN
3379    MT      568        C                 CC     2.0 8.0
3379    MT      568        C                CCC     2.0 8.0
3379    MT      568        C               CCCC     2.0 8.0
3379    MT      568        C              CCCCC     2.0 8.0
3379    MT      568        C             CCCCCC     2.0 8.0
3379    MT      568        C            CCCCCCC     2.0 8.0
3379    MT      568        C           CCCCCCCC     2.0 8.0