简体   繁体   English

在熊猫数据框中创建一行

[英]Create a row in pandas dataframe

I am trying to create a row in my existing pandas dataframe and the value of a new row should be a computation我正在尝试在现有的 Pandas 数据框中创建一行,新行的值应该是一个计算

I have a dataframe that looks like the below:我有一个如下所示的数据框:

Rating  LE_St  % Total
1.00    7.58        74.55 
2.00    0.56        5.55 
3.00    0.21        2.04 
5.00    0.05        0.44 
6.00    1.77       17.42 
All    10.17       100.00

I want to add a row called "Metric" which is the sum of "LE_St" variable for "Rating" >= 4 and <6 divided by "LE_St" for "All" ie Metric = (0.05+1.77)/10.17 My output dataframe should look like below:我想添加一个名为“Metric”的行,它是“Rating”>= 4 和 <6 的“LE_St”变量之和除以“All”的“LE_St”,即 Metric = (0.05+1.77)/10.17 我的输出数据框应如下所示:

Rating  LE_St  % Total
1.00    7.58        74.55 
2.00    0.56        5.55 
3.00    0.21        2.04 
5.00    0.05        0.44 
6.00    1.77       17.42 
All    10.17       100.00
Metric  0.44

I believe your approach to the dataframe is wrong.我相信您对数据框的处理方法是错误的。 Usually rows hold values correlating with columns in a matter that makes sense and not hold random information.通常,行包含与列相关的值,这些值有意义且不包含随机信息。 the power of pandas and python is for holding and manipulating data. pandas 和 python 的强大之处在于保存和操作数据。 You can easily compute a value from a column or even all columns and store them in a "summary" like dataframe or in separate values.您可以轻松地从一列甚至所有列计算一个值,并将它们存储在“摘要”中,如数据帧或单独的值。 That might help you with this as well.这也可能对您有所帮助。 for computation on a column (ie Series object) you can use the .sum() method (or any other of the computational tools ) and slice your dataframe by values in the "rating" column.对于列(即系列对象)的计算,您可以使用 .sum() 方法(或任何其他计算工具)并按“评级”列中的值对数据框进行切片。 for random computation of small statistics you will be rather off with excel :)对于小统计的随机计算,你会很不喜欢 excel :)

an example of a solution might look like this:解决方案的示例可能如下所示:

all = 10.17 # i dont know where this value comes from
df = df[df['rating'].between(4, 6, inclusive=True)]
metric = sliced_df['LE_ST'].sum()/all

print metric # or store it somewhere however you like

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM