根据最新列修改Pandas Dataframe列

时间:2017-06-18 15:53:06

标签: python pandas

我的pandas.DataFrame看起来像这样:

runseq  custid  m6    m7
 1       123    x     y
 1       345    y     z
 1       213    a     b
 2       123    a     c
 2       345    z     w
 2       213    x     k
 3       123    m     n
 3       345    o     p
 3       213    a     b

我希望所有以前的runseq(1,2)m6m7值都替换为最新的runseq(3)。像这样:

runseq  custid  m6    m7
 1       123    m     n
 1       345    o     p
 1       213    a     b
 2       123    m     n
 2       345    o     p
 2       213    a     b
 3       123    m     n
 3       345    o     p
 3       213    a     b

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

可以使用pandas.DataFrame.update()

完成此操作

代码:

new_values = df[df.runseq == 3][['custid', 'm6', 'm7']].set_index('custid')
df = df.set_index('custid')
df.update(new_values)
df = df.reset_index()

测试代码:

df = pd.read_fwf(StringIO(u"""
    runseq  custid  m6    m7
     1       123    x     y
     1       345    y     z
     1       213    a     b
     2       123    a     c
     2       345    z     w
     2       213    x     k
     3       123    m     n
     3       345    o     p
     3       213    a     b"""), header=1)

new_values = df[df.runseq == 3][['custid', 'm6', 'm7']].set_index('custid')
df = df.set_index('custid')
df.update(new_values)
df = df.reset_index()
print(df)

结果:

   custid  runseq m6 m7
0     123       1  m  n
1     345       1  o  p
2     213       1  a  b
3     123       2  m  n
4     345       2  o  p
5     213       2  a  b
6     123       3  m  n
7     345       3  o  p
8     213       3  a  b

答案 1 :(得分:0)

您可以使用pivot进行重塑,如果DataFrame.where[HttpPost] public ActionResult YourAction(YourModel model) { // your condition here ModelState.Remove("location_txt_box "); // to omit specific field according to condition if (ModelState.IsValid) { // your code here } return View(); } )和bfill没有最后一行,则NaNs可以使用stack重塑:

method='bfill'

另一种解决方案:

您可以使用numpy.tile重复转置值:

df1 = df.pivot(index='runseq',columns='custid')
mask = pd.Series((df1.index == df['runseq'].iat[-1]), index=df1.index)
#if necessary add ffill for forward filling NaNs
#df1 =  df1.where(mask).bfill().ffill().stack().reset_index()
df1 =  df1.where(mask).bfill().stack().reset_index()
print (df1)
0       1     123  m  n
1       1     213  a  b
2       1     345  o  p
3       2     123  m  n
4       2     213  a  b
5       2     345  o  p
6       3     123  m  n
7       3     213  a  b
8       3     345  o  p