代码如下:
import pandas as pd
sum_row1 = table2.loc['row_1', 'D'] = table2.loc['row_1'].sum()
sum_row2 = table2.loc['row_1', 'D'] = table2.loc['row_2'].sum()
sum_row3 = table2.loc['row_1', 'D'] = table2.loc['row_3'].sum()
sum_row4 = table2.loc['row_1', 'D'] = table2.loc['row_4'].sum()
table2 = pd.DataFrame( data= [[11,21,10, sum_row1], [10, 30, 20, sum_row2], [11, 41, 30, sum_row3], [50, -100, 30, sum_row4] ] , index = ['row_1', 'row_2', 'row_3', 'row_4'], columns = ['B', 'D', 'E', 'sum'])
table2
结论:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
c:\Users\*USER*\Documents\hw7.ipynb Cell 1' in <cell line: 3>()
1 import pandas as pd
----> 3 sum_row1 = table2.loc['row_1', 'D'] = table2.loc['row_1'].sum()
4 sum_row2 = table2.loc['row_1', 'D'] = table2.loc['row_2'].sum()
5 sum_row3 = table2.loc['row_1', 'D'] = table2.loc['row_3'].sum()
NameError: name 'table2' is not defined
有任何想法吗?
改变:
import pandas as pd
table2 = pd.DataFrame( data= [[11,21,10, sum_row1], [10, 30, 20, sum_row2], [11, 41, 30, sum_row3], [50, -100, 30, sum_row4] ] , index = ['row_1', 'row_2', 'row_3', 'row_4'], columns = ['B', 'D', 'E', 'sum'])
sum_row1 = table2.loc['row_1', 'D'] = table2.loc['row_1'].sum()
sum_row2 = table2.loc['row_1', 'D'] = table2.loc['row_2'].sum()
sum_row3 = table2.loc['row_1', 'D'] = table2.loc['row_3'].sum()
sum_row4 = table2.loc['row_1', 'D'] = table2.loc['row_4'].sum()
table2
新输出:
NameError Traceback (most recent call last)
c:\Users\*USER*\Documents\hw7.ipynb Cell 1' in <cell line: 3>()
1 import pandas as pd
----> 3 table2 = pd.DataFrame( data= [[11,21,10, sum_row1], [10, 30, 20, sum_row2], [11, 41, 30, sum_row3], [50, -100, 30, sum_row4] ] , index = ['row_1', 'row_2', 'row_3', 'row_4'], columns = ['B', 'D', 'E', 'sum'])
5 sum_row1 = table2.loc['row_1', 'D'] = table2.loc['row_1'].sum()
6 sum_row2 = table2.loc['row_1', 'D'] = table2.loc['row_2'].sum()
NameError: name 'sum_row1' is not defined
首先您需要创建一个表格,然后填写它。该列
sum
在所有行之后并立即填充: