关于获取python数据帧的行和
我有以下python数据帧关于获取python数据帧的行和,python,pandas,for-loop,while-loop,Python,Pandas,For Loop,While Loop,我有以下python数据帧 data={'1':[1,1,1,1],'2':[1,1,1,1],'3':[1,1,1,1]} df=pd.DataFrame(data) 我需要以这样的方式获得行的总和,这样我的最终输出应该是这样的, 因此,在这个期望的输出中,第二列应该包含原始数据帧第二列的行总和。等等 为了得到这个输出,我编写了以下代码 sum_mat=np.zeros(shape=(3,3)) numOfIteration=3 itr=list(range(0,numOfIterat
data={'1':[1,1,1,1],'2':[1,1,1,1],'3':[1,1,1,1]}
df=pd.DataFrame(data)
我需要以这样的方式获得行的总和,这样我的最终输出应该是这样的,
因此,在这个期望的输出中,第二列应该包含原始数据帧第二列的行总和。等等
为了得到这个输出,我编写了以下代码
sum_mat=np.zeros(shape=(3,3))
numOfIteration=3
itr=list(range(0,numOfIteration))
for i in range(0,3):
for j in range(0,3):
while i <= itr[i]:
sum_mat[i,j]+= df.iloc[i,j]
print (sum_mat)
这应该行得通这也行得通
for i,row in df.iterrows(): #go through each row
df.loc[i]=df.loc[i].cumsum() #assign each row as the cumulative sum of the row
输出:
>>> df
1 2 3
0 1 2 3
1 1 2 3
2 1 2 3
3 1 2 3
编辑
我们可以做:
df=df.cumsum(axis=1)
使用函数查找迄今为止沿列轴看到的值的累积和
Ex.
import pandas as pd
data = {'1': [1, 1, 1, 1], '2': [1, 1, 1, 1], '3': [1, 1, 1, 1]}
df = pd.DataFrame(data)
print("before")
print(df)
df = df.cumsum(axis=1)
print("after")
print(df)
O/p:
以前
1 2 3
0 1 1 1
1 1 1 1
2 1 1 1
3 1 1 1
之后
df=df.cumsum(axis=1)
import pandas as pd
data = {'1': [1, 1, 1, 1], '2': [1, 1, 1, 1], '3': [1, 1, 1, 1]}
df = pd.DataFrame(data)
print("before")
print(df)
df = df.cumsum(axis=1)
print("after")
print(df)
1 2 3
0 1 1 1
1 1 1 1
2 1 1 1
3 1 1 1
1 2 3
0 1 2 3
1 1 2 3
2 1 2 3
3 1 2 3