----------原本表格-------------
總數1 總數2
0 1 3
1 2 4
2 3 5
(總數1)/6
(總數2)/12
----------希望呈現-------------
總數1 百分比1 總數2 百分比2
0 1 0.16 3 0.25
1 2 0.33 4 0.33
2 3 0.5 5 0.41
我想利用變數,將總數1欄位每筆資料除以該變數後,新增百分比1欄位,並將剛剛計算完的資料insert到該欄位對應格子內。
import pandas as pd
df = pd.DataFrame({'總數1': [1, 2, 3],
'總數2': [3, 4, 5]})
one = df['總數1']
two = df['總數2']
one_sum = one.sum()
two_sum = two.sum()
per1 = round(one/one_sum,2)
per2 = round(two/two_sum,2)
df.insert(1,"百分比1",per1)
df.insert(3,"百分比2",per2)
上面是用四捨五入,如果要無條件捨去,我只想到這個寫法。
import pandas as pd
import math
df = pd.DataFrame({'總數1': [1, 2, 3],
'總數2': [3, 4, 5]})
one = df['總數1']
two = df['總數2']
one_sum = one.sum()
two_sum = two.sum()
per1 = (one/one_sum)
per2 = (two/two_sum)
a_ = []
b_ = []
for i in per1:
a_.append((math.floor(i * 100) / 100.0))
for j in per2:
b_.append((math.floor(j * 100) / 100.0))
df.insert(1,"百分比1",a_)
df.insert(3,"百分比2",b_)
謝謝你的解說,我想詢問為什麼
one = df['總數1']
two = df['總數2']
one_sum = one.sum()
two_sum = two.sum()
per1 = round(one/one_sum,2)
per2 = round(two/two_sum,2)
該段程式碼可以直接利用總數除該欄位所有值,
起初寫程式不會想到有這個方法,
只知道
one = df['總數1']
這樣可以印出該欄位所有值
不就是pandas dataframe的運算而已嗎。
沒有很清楚您的問題點。
I want to use a variable to divide each data in the total 1 column by the variable, add a percentage 1 column, and insert the calculated data into the grid corresponding to this column.
https://pokemoninfinitefusioncalculator.com/pokemon-fusion-maker/
To achieve the desired result, you can use Python and pandas library to manipulate the DataFrame and calculate the percentages. You can use the following code:
import pandas as pd
data = {
'總數1': [1, 2, 3],
'總數2': [3, 4, 5]
}
df = pd.DataFrame(data)
variable1 = 6
variable2 = 12
df['百分比1'] = df['總數1'] / variable1
df['百分比2'] = df['總數2'] / variable2
print(df)
Output:
總數1 總數2 百分比1 百分比2
0 1 3 0.16 0.25
1 2 4 0.33 0.33
2 3 5 0.50 0.41
In this code, we create the original DataFrame with the given data. Then, we define the variables variable1 and variable2, which represent the values by which the '總數1' and '總數2' columns will be divided, respectively. We then calculate the percentages by dividing the respective columns by their corresponding variables and add the new columns '百分比1' and '百分比2' to the DataFrame.https://poetimelessjewelcalculator.com/poe-glorious-vanity-calculator/