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

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

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:

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]})
data = data.set_index('Tissues')

The dataframe is:

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

And two dictionaries:

wts_m1 = {'a1':0.5, 'x2':0.25, 'y3':0.25}
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

这是一种方法:

# 计算数值
M = (data.index.map(wts_m1) * data['M']).sum()
F = (data.index.map(wts_m1) * data['F']).sum()

# 将行创建为DataFrame
sr = pd.DataFrame({'M': [M,],'F': [F,]}, index=['m1'])

# 连接数据
pd.concat([data, sr], axis=0)

你也可以这样做:

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

Here's a way to do:

# calculate values
M = (data.index.map(wts_m1) * data['M']).sum()
F = (data.index.map(wts_m1) * data['F']).sum()

# create the row as df    
sr = pd.DataFrame({'M': [M,],'F': [F,]}, index=['m1'])

# join data
pd.concat([data, sr], axis=0)

a1  1.00   8.00
x2  2.00   9.00
y3  3.00  10.00
b   4.00  11.00
c1  5.00  12.00
c2  6.00  13.00
c3  7.00  14.00
m1  1.75   8.75

You can also do:

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:

确定