使用公式向数据框添加一行

huangapple go评论186阅读模式
英文:

Add a row to a dataframe using formula

问题

我想要将一行添加到名为'm1'的数据框中,其中'M'的值由以下计算得出:1x0.5+2x0.25+3x0.25,'F'的值由以下计算得出:8x0.5+9x0.25+10x0.25,其中0.5、0.25和0.25来自wts_m1。

同样,对于m2,权重来自wts_m2。

英文:

I have a dataframe that looks like this:

  1. data = pd.DataFrame({'Tissues':['a1','x2','y3','b','c1','v2','w3'], 'M':[1,2,3,4,5,6,7], 'F':[8,9,10,11,12,13,14]})
  2. data = data.set_index('Tissues')

The dataframe is:

  1. M F
  2. Tissues
  3. a1 1 8
  4. x2 2 9
  5. y3 3 10
  6. b 4 11
  7. c1 5 12
  8. v2 6 13
  9. w3 7 14

And two dictionaries:

  1. wts_m1 = {'a1':0.5, 'x2':0.25, 'y3':0.25}
  2. wts_m2 = {'c1':0.333, 'v2': 0.667}

I want to add a row to the dataframe called 'm1', where the values for 'M' are given by: 1x0.5+2*0.25+3*0.25 and those for 'F' are given by 8x0.5+9*0.25+10*0.25, where 0.5, 0.25 and 0.25 come from wts_m1.

And similarly for m2, where the weights come from wts_m2.

答案1

得分: 2

这是一种方法:

  1. # 计算数值
  2. M = (data.index.map(wts_m1) * data['M']).sum()
  3. F = (data.index.map(wts_m1) * data['F']).sum()
  4. # 将行创建为DataFrame
  5. sr = pd.DataFrame({'M': [M,],'F': [F,]}, index=['m1'])
  6. # 连接数据
  7. pd.concat([data, sr], axis=0)

你也可以这样做:

  1. data.loc['m1'] = [M, F]
英文:

Here's a way to do:

  1. # calculate values
  2. M = (data.index.map(wts_m1) * data['M']).sum()
  3. F = (data.index.map(wts_m1) * data['F']).sum()
  4. # create the row as df
  5. sr = pd.DataFrame({'M': [M,],'F': [F,]}, index=['m1'])
  6. # join data
  7. pd.concat([data, sr], axis=0)
  8. a1 1.00 8.00
  9. x2 2.00 9.00
  10. y3 3.00 10.00
  11. b 4.00 11.00
  12. c1 5.00 12.00
  13. c2 6.00 13.00
  14. c3 7.00 14.00
  15. m1 1.75 8.75

You can also do:

  1. data.loc['m1'] = [M, F]

huangapple
  • 本文由 发表于 2020年1月7日 00:45:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定