python pandas 在dataframe中增加或删除行或列

在dataframe中增加或删除行或列

首先构建一个dataframe

import pandas as pd
d={'one':{'a':1,'b':2,'c':3},'two':{'a':4,'b':5,'c':6},'three':{'a':7,'b':8,'c':9}}
df=pd.DataFrame(d)
print(df)

构建的dataframe为:

one two three
a 1 4 7
b 2 5 8
c 3 6 9

在dataframe中增加一列

df['four']=[10,11,12]
print(df)

结果为:

one two three four
a 1 4 7 10
b 2 5 8 11
c 3 6 9 12

把第四列内容更改:

df['four']=[13,14,15]
print(df)

结果为:

one two three four
a 1 4 7 13
b 2 5 8 14
c 3 6 9 15

在dataframe中增加一行

df.loc['d']=[2,4,6,8]
print(df)

结果为:

one two three four
a 1 4 7 13
b 2 5 8 14
c 3 6 9 15
d 2 4 6 8

在dataframe中删除特定的列

df=df.drop(columns='four')#或者写为:df.drop(columns='four',inplace=True)
#或者del df['four']
print(df)

结果为:

one two three
a 1 4 7
b 2 5 8
c 3 6 9
d 2 4 6

在dataframe中删除特定的行

df.drop(index='d',inplace=True)
print(df)

结果为:

one two three
a 1 4 7
b 2 5 8
c 3 6 9

在dataframe中插入特定的列

df.insert(0,'zero',[10,11,12])
#df.insert(添加列位置索引序号,添加列名,数值)
print(df)

结果为:

zero one two three
a 10 1 4 7
b 11 2 5 8
c 12 3 6 9

在dataframe中插入特定的行

在dataframe中特定的位置插入一行是没有什么好的方法的。不过倒是可以通过别的方法间接得到:
首先加入想要加入的行,然后增加一列,设计好该列中每一行应该对应的值,然后按照该列对所有的行进行排序,排序之后,再把该列删掉即可。
例如我要在第一行,第二行之间插入一行,行名为“line”,值为[2,4,6,8]。可以这么做:

df.loc['line']=[2,4,6,8]
df['change']=[1,3,4,2]
df=df.sort_values(by='change')
df.drop(columns='change',inplace=True)
print(df)

结果为:

zero one two three
a 10 1 4 7
line 2 4 6 8
b 11 2 5 8
c 12 3 6 9

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值