0

## python dataframe 計算

``````----------原本表格-------------
總數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 個回答

0
Wilion
iT邦新手 4 級 ‧ 2021-07-20 20:25:21

``````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)
``````

Wilion iT邦新手 4 級 ‧ 2021-07-20 22:18:34 檢舉

``````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_)
``````

cgc0800 iT邦新手 5 級 ‧ 2021-07-20 23:04:24 檢舉

``````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']
``````

Wilion iT邦新手 4 級 ‧ 2021-07-21 10:09:20 檢舉