如何在pandas中的DataFrame中插入行?(Python)
假设我有以下数据帧:如何在pandas中的DataFrame中插入行?(Python),python,pandas,dataframe,row,Python,Pandas,Dataframe,Row,假设我有以下数据帧: a=np.array([[10,20,30,40],[5,20,35,50],[0,5,10,15]]) b=pd.DataFrame(a, columns=["n1", "n2", "n3", "n4"]) 我对其进行以下计算(第一排和第二排之间的差异): 然后我想将这一行差异(由c.loc[[1]]给出)插入我的数据框b。我该怎么做?当我尝试时,我得到一个错误ValueError:无法设置列不匹配的行“try c = b.diff(axis=0).iloc[1] 或
a=np.array([[10,20,30,40],[5,20,35,50],[0,5,10,15]])
b=pd.DataFrame(a, columns=["n1", "n2", "n3", "n4"])
我对其进行以下计算(第一排和第二排之间的差异):
然后我想将这一行差异(由c.loc[[1]]
给出)插入我的数据框b
。我该怎么做?当我尝试时,我得到一个错误ValueError:无法设置列不匹配的行“
try
c = b.diff(axis=0).iloc[1]
或
输出:
print(c)
n1 -5.0
n2 0.0
n3 5.0
n4 10.0
Name: 1, dtype: float64
要将c添加到b,请使用append
b = b.append(c)
打印输出(b)
试一试
或
输出:
print(c)
n1 -5.0
n2 0.0
n3 5.0
n4 10.0
Name: 1, dtype: float64
要将c添加到b,请使用append
b = b.append(c)
打印输出(b)
由loc
选择的系列
和一个[]
使用:
b.loc[len(b)] = b.diff().loc[1]
print (b)
n1 n2 n3 n4
0 10.0 20.0 30.0 40.0
1 5.0 20.0 35.0 50.0
2 0.0 5.0 10.0 15.0
3 -5.0 0.0 5.0 10.0
或与数据帧一起使用[[]]
:
c = pd.concat([b, b.diff().loc[[1]]], ignore_index=True)
print (c)
n1 n2 n3 n4
0 10.0 20.0 30.0 40.0
1 5.0 20.0 35.0 50.0
2 0.0 5.0 10.0 15.0
3 -5.0 0.0 5.0 10.0
由loc
选择的系列
和一个[]
使用:
b.loc[len(b)] = b.diff().loc[1]
print (b)
n1 n2 n3 n4
0 10.0 20.0 30.0 40.0
1 5.0 20.0 35.0 50.0
2 0.0 5.0 10.0 15.0
3 -5.0 0.0 5.0 10.0
或与数据帧一起使用[[]]
:
c = pd.concat([b, b.diff().loc[[1]]], ignore_index=True)
print (c)
n1 n2 n3 n4
0 10.0 20.0 30.0 40.0
1 5.0 20.0 35.0 50.0
2 0.0 5.0 10.0 15.0
3 -5.0 0.0 5.0 10.0