Pandas数据结构之DataFrame选择、删除、添加列

在pandas中可以使用类似于字典的方式来对DataFrame中的列对象进行选择、添加、删除

选择列

可以直接使用 [column_name] 来选择一个列,类似于字典的索引操作,column_name相当于字典中的键,键所对应的值为一个Series对象,即一个列。另外和字典类似,当使用 [ ] 的方式索引一个不存在的键时会报错

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
df1 = df['one']
# df1的值为:
# a    1.0
# b    2.0
# c    3.0
# d    NaN    
# Name: one, dtype: float64

df1 = df['three']
# 此处会报错:KeyError: 'three'

也可以使用 get(column_name, default) 方法来获取一个列,当column_name对应的列存在于DataFrame中时返回该列,当不存在时,则返回default指定的内容,这一点和python字典的用法也是一致的。需要注意的是,default可以指定任何内容

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
df1 = df.get('one')
df2 = df.get('three', 1)
# df1的值为:
# a    1.0
# b    2.0
# c    3.0
# d    NaN
# Name: one, dtype: float64
# df2的值为:1

删除列

可以使用python的 del 关键字删除DataFrame中的某一列,同样可以使用 [ ] 来指定选中的要删除的列

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
del df['one']
# 此时,df的内容变为:
#      two
# a    1.0
# b    2.0
# c    3.0
# d    4.0

也可以使用pop(column_name, default)方法删除一列,如果column_name对应的列名存在于DataFrame中,则删除该列并返回删除的该列,否则返回default,同样,default可以是任何内容

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
df1 = df.pop('one')

添加列

添加的时候也类似于dict,可以直接使用 df[column_name] 进行赋值,如果column_name对应的列不存在,则创建该列,赋予的值可以是一个标量也可以是一个Series,或者是一个ndarray,当值是一个标量的时候,该标量会进行广播,当值是一个ndarray时,ndarray的长度必须和DataFrame的index的长度相同,否则会报错

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
df['foo'] = 'bar'
# 此时df的值变为
#      one    two    foo
# a    1.0    1.0    bar
# b    2.0    2.0    bar
# c    3.0    3.0    bar
# d    NaN    4.0    bar

# 当使用Series作为值时,需要指定index,否则df['foo']的值全为NaN,
# 因为此时该Series的默认index为['0', '1', '2', '3'],都不匹配df中的索引
df['foo'] = pd.Series([1.0, 2.0, 3.0, 4.0], index=['a', 'b', 'c', 'e'])
# 此时df的值为:
#      one    two    foo
# a    1.0    1.0    1.0
# b    2.0    2.0    2.0
# c    3.0    3.0    3.0
# d    NaN    4.0    NaN

# ndarray的长度必须等于DataFrame的index的长度
# np.array(4)或者np.array((4))也是可以的,
# 因为它会被当成一个标量看待,然后进行广播,foo中的每一个值均为4
df['foo'] = np.random.randn((4))
# 此时df的值为:
#      one    two    foo
# a    1.0    1.0    -0.007800
# b    2.0    2.0    -0.421174
# c    3.0    3.0    0.172283
# d    NaN    4.0    -0.854485

另一种方法就是 insert(loc, name, value) 方法,该方法可以指定要插入的位置,value表示列的值,可以是标量、Series、ndarray,原则同上,name表示新插入的列的名称,loc表示插入到哪个列,使用数字表示,从0开始,0表示插入为第一列

import numpy as np
d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
# 插入为第1列,列名为 bar,值为第0列的值
df.insert(1, "bar", df["one"])
# 此时df的值为:
#      one    bar    two
# a    1.0    1.0    1.0
# b    2.0    2.0    2.0
# c    3.0    3.0    3.0
# d    NaN    NaN    4.0

pandas还提供了一个assign(**kwargs) 方法来添加一个新的列,该方法允许使用已有的数据生成新的列,返回一个新的DataFrame对象,即该方法不会对用来生成新数据的DataFrame产生影响,此外该方法可以同时添加多个列。需要注意的是assign方法的参数要求是关键字参数,关键字的键和值分别对应新添加的列的列名和值。该方法还可以传入一个方法,该方法可以生成一个列数据

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
df1 = df.assign(foo=df['one'] / df['two'])
# df1的结果为:
#      one    two    foo
# a    1.0    1.0    1.0
# b    2.0    2.0    1.0
# c    3.0    3.0    1.0
# d    NaN    4.0    NaN
# df1不会影响df

# 传入一个函数的情况,此时df2和df1的结果相同
df2 = df.assign(foo=lambda df: df['one'] / df['two'])
# 添加多个列的方法,即传入多个关键字参数,关键字的顺序和添加后的顺序一致
df3 = df.assign(foo=lambda df: df['one'] / df['two'], bar=df['one'] - df['two'])
# df3的值为:
#      one    two    foo    bar
# a    1.0    1.0    1.0    0.0
# b    2.0    2.0    1.0    0.0
# c    3.0    3.0    1.0    0.0
# d    NaN    4.0    NaN    NaN
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值