本帖最后由 ymhld 于 2020-5-16 15:00 编辑
如何实现两行直接相加
列的会,data['列1']=data['列2']+data['列3']
有没有行直接相加的方法
如下代码也能实现N1+N2
[Python] 纯文本查看 复制代码 import pandas as pd
chengji = [['N', 95,0], ['N', 100,88], ['N', 88,100],['N', 66,0]]
data=pd.DataFrame(chengji ,columns=['p','x','g'])
data1=data[['p','x']].copy()
data1['p']=data1.index.map(lambda x:"N"+str(x+1))
print(data1)
data.loc[:,'p']=data.index.map(lambda x:"N"+str(x+1))
# print(data)
# data.columns=['p','营业成本本年累计','营业收入本年累计',]
# print(data)
# data['Q']=0
# data.loc[data['营业收入本年累计']!=0,'Q']=data['营业成本本年累计']/data['营业收入本年累计']
print(data)
heji=['N1+N2',['N1','N2']]
print(data.loc[data['p'].isin(heji[1])])
data.loc[heji[0]]=data.loc[data['p'].isin(heji[1])].sum()
data.loc[heji[0],'p']=heji[0]
print(data)
data.drop(data['p'].isin(heji[1]),inplace=True)
print(data)
|