欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pandas dataframe 添加行和列

程序员文章站 2022-05-25 17:08:44
...
import numpy as np
import pandas as pd

df=pd.DataFrame(np.random.randn(3,4),columns=list("ABCD"),index=list("xyz"))
# print(df)
res1=df.apply(lambda x:x.sum())
# print(res1)
# print(type(res1))  #<class 'pandas.core.series.Series'>

#添加行
df.loc['newrow']=res1
# print(df)
#添加列
res2=df.apply(lambda x:x.sum(),axis=1)
# print(res2)
df['newcolumn']=res2
# print(df)

'''
apply 函数    官网
'''

df = pd.DataFrame([[4, 9],] * 3, columns=['A', 'B'])


# print(df.apply(np.sqrt))
df[['new1','new2']]=df.apply(np.sqrt)
print(df)

# df.loc['newr1','newr2','new3']= df.apply(np.sqrt,axis=1)



res=df.apply(np.sqrt,axis=1)  #<class 'pandas.core.frame.DataFrame'>
print(res)
df=pd.concat([res,df])
print(df)


相关标签: da ta frame