# 【4.1.2】Pandas--DataFrame对行或列运算添加新行和列

## 一、行或列求和

from pandas import DataFrame
import pandas as pd
import numpy as np


df = DataFrame(np.random.randn(4, 5), columns=['A', 'B', 'C', 'D', 'E'])


DataFrame数据预览：

          A         B         C         D         E
0  0.673092  0.230338 -0.171681  0.312303 -0.184813
1 -0.504482 -0.344286 -0.050845 -0.811277 -0.298181
2  0.542788  0.207708  0.651379 -0.656214  0.507595
3 -0.249410  0.131549 -2.198480 -0.437407  1.628228


df['Col_sum'] = df.apply(lambda x: x.sum(), axis=1)


df.loc['Row_sum'] = df.apply(lambda x: x.sum())


                A         B         C         D         E   Col_sum
0        0.673092  0.230338 -0.171681  0.312303 -0.184813  0.859238
1       -0.504482 -0.344286 -0.050845 -0.811277 -0.298181 -2.009071
2        0.542788  0.207708  0.651379 -0.656214  0.507595  1.253256
3       -0.249410  0.131549 -2.198480 -0.437407  1.628228 -1.125520
Row_sum  0.461987  0.225310 -1.769627 -1.592595  1.652828 -1.022097


## 二、列或者行统计每一行0值的个数

    df = pd.DataFrame({'a':[1,0,0,1,3],'b':[0,0,1,0,1],'c':[0,0,0,0,0]})
df

a  b  c
0  1  0  0
1  0  0  0
2  0  1  0
3  1  0  0
4  3  1  0

(df == 0).astype(int).sum(axis=1)

0    2
1    3
2    2
3    2
4    1
dtype: int64

df == 0

a      b     c
0  False   True  True
1   True   True  True
2   True  False  True
3  False   True  True
4  False  False  True

(df == 0).astype(int)

a  b  c
0  0  1  1
1  1  1  1
2  1  0  1
3  0  1  1

4  0  0  1


df.apply(lambda x : x.value_counts().get(0,0),axis=1)

0    2
1    3
2    2
3    2
4    1
dtype: int64


1. value_counts 如果想升序排列，设置参数 ascending = True。print(df[‘区域’].value_counts(ascending=True))
2. 如果想得出计数占比，可以加参数 normalize=True：

df_species['Total_hit'] = df_species.apply(lambda x : len(uniq_ids)-x.value_counts().get(0,0),axis=1)
one_line_total = df_species.apply(lambda x : len(df_species)-x.value_counts().get(0,0),axis=0)

one_line_sum = df_species.apply(lambda x : x.sum(),axis=0)

df_species.loc['Total_hit'] = one_line_total
df_species.loc['Sum'] = one_line_sum


## 参考资料

https://www.cnblogs.com/wuzhiblog/p/python_new_row_or_col.html