@pandas中行和列操作(“增,删,改")
前言
主要了解“增,删,改”
一、增
1.一维
代码如下(示例):
如果加入的索引是一样的添加的数据可以为行上,否则 反之!
pf = pd.DataFrame(np.arange(1,17).reshape(4,4),index=["a","b","c","d"],columns=["A","B","C","D"])
# A B C D
# a 1 2 3 4
# b 5 6 7 8
# c 9 10 11 12
# d 13 14 15 16
pf["f"] = 17 # 会改变原来的数据
print(pf)
# A B C D f
# a 1 2 3 4 17
# b 5 6 7 8 17
# c 9 10 11 12 17
# d 13 14 15 16 17
s1 = pd.Series(np.arange(4),index=["A","B","C","D"])
p = pf.append(s1,ignore_index=True)
print(p)
# A B C D f
# 0 1.0 2.0 3.0 4.0 17.0
# 1 5.0 6.0 7.0 8.0 17.0
# 2 9.0 10.0 11.0 12.0 17.0
# 3 13.0 14.0 15.0 16.0 17.0
# 4 0.0 1.0 2.0 3.0 NaN
dirt1 = {
"city":["上海","天津","厦门"],
"name":["小A","小B","小白"],
"sex":["12","34","25"]
}
arr1 = pd.DataFrame(dirt1)
print(arr1)
# city name sex
# 0 上海 小A 12
# 1 天津 小B 34
# 2 厦门 小白 25
dirt2 = {
"city":"深圳",
"name":"小黑",
"sex":"17"
}
arr2 = arr1.append(dirt2,ignore_index=True)
print(arr2)
# city name sex
# 0 上海 小A 12
# 1 天津 小B 34
# 2 厦门 小白 25
# 3 深圳 小黑 17
2.二维
dirt1 = {
"city":["上海","天津","厦门"],
"name":["小A","小B","小白"],
"sex":["12","34","25"]
}
arr1 = pd.DataFrame(dirt1)
print(arr1)
# city name sex
# 0 上海 小A 12
# 1 天津 小B 34
# 2 厦门 小白 25
p = arr1.insert(3,"age",[99,99,99]) # 插入的位置 列名 列值
print(arr1)
# city name sex age
# 0 上海 小A 12 99
# 1 天津 小B 34 99
# 2 厦门 小白 25 99
arr1["work"] = ["程序员","CEO","主持人"]
print(arr1)
# city name sex age work
# 0 上海 小A 12 99 程序员
# 1 天津 小B 34 99 CEO
# 2 厦门 小白 25 99 主持人
2.删
del drop( self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=“raise” )
1.一维
代码如下(示例):
arr1 = pd.Series(np.arange(6))
arr2 = arr1.drop(2) # 不改变原来数据
print(arr2)
del arr1[1] # 改变原来数据
print(arr1)
2.二维
代码如下(示例):
pf = pd.DataFrame(np.arange(1,17).reshape(4,4),columns=["A","B","C","D"])
sc1 = pf.drop("A",axis=1) # 删列 axis确定方向
print(sc1)
sc2 = pf.drop(2) # 删行 (默认)
print(sc2)
del pf["A"] # del 可以删列 不可删行
print(pf)
2.改
1.改内容
只能改列,如果你要改的列没有就会添加一列 要改行或者具体的一个数可以借助loc,iloc 代码如下(示例):
pf = pd.DataFrame(np.arange(1,17).reshape(4,4),columns=["A","B","C","D"])
pf["B"]=["20","60","100","140"]
print(pf)
pf.loc[0]=["20","60","100","140"]
pf.iloc[1,1]="dog"
print(pf)
2. 改标签名
借助 remane 代码如下(示例):
pf = pd.DataFrame(np.arange(1,17).reshape(4,4),columns=["A","B","C","D"])
pf.rename(index={1:"one"},columns={"C":"c"},inplace=True)
print(pf)
总结
索引切片就是查
|