Python Pandas 对列/行进行选择,增加,删除操作

一、列操作

1.1 选择列

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
  'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print (df ['one'])
# 选择其中一列进行显示,列长度为最长列的长度
# 除了 index 和 数据,还会显示 列表头名,和 数据 类型

运行结果:

a    1.0
b    2.0
c    3.0
d    NaN
Name: one, dtype: float64

1.2 增加列

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
  'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)

# Adding a new column to an existing DataFrame object with column label by passing new series

print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,30,20],index=['a','c','b'])
print(df)
# 增加列后进行显示,其中 index 用于对应到该列 元素 位置(所以位置可以不由 列表 中的顺序进行指定)

print ("Adding a new column using the existing columns in DataFrame:")
df['four']=df['one']+df['two']+df['three']
print(df)
# 我们选定列后,直接可以对整个列的元素进行批量运算操作,这里 NaN 与其他元素相加后,还是 NaN

运行结果:

Adding a new column by passing as Series:
   one  two  three
a  1.0    1   10.0
b  2.0    2   20.0
c  3.0    3   30.0
d  NaN    4    NaN
Adding a new column using the existing columns in DataFrame:
   one  two  three  four
a  1.0    1   10.0  12.0
b  2.0    2   20.0  24.0
c  3.0    3   30.0  36.0
d  NaN    4    NaN   NaN

1.3 删除列(del 和 pop 函数)

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
  'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
  'three' : pd.Series([10,20,30], index=['a','b','c'])}

df = pd.DataFrame(d)
print ("Our dataframe is:")
print(df)

# 使用 del 函数
print ("Deleting the first column using DEL function:")
del(df['one'])
print(df)

# 使用 pop 函数
print ("Deleting another column using POP function:")
df_2=df.pop('two') # 将一列 pop 到新的 dataframe
print(df_2)
print(df)

运行结果:

Our dataframe is:
   one  two  three
a  1.0    1   10.0
b  2.0    2   20.0
c  3.0    3   30.0
d  NaN    4    NaN
Deleting the first column using DEL function:
   two  three
a    1   10.0
b    2   20.0
c    3   30.0
d    4    NaN
Deleting another column using POP function:
   three
a   10.0
b   20.0
c   30.0
d    NaN
POP column:
a    1
b    2
c    3
d    4
Name: two, dtype: int64

二、行操作

2.1 选择行

2.1.1 通过 label 选择行(loc 函数)

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
  'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df.loc['b']) # 显示这一行中,对应表头 下的 对应数据,同时显示 行 index 和 数据类型

运行结果:

one    2.0
two    2.0
Name: b, dtype: float64

2.1.2 通过序号选择行(iloc 函数)

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
  'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df.iloc[2]) # 序号 2 对应的是第 3 行的数据

运行结果:

one    3.0
two    3.0
Name: c, dtype: float64

2.1.3 通过序号选择行切片

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
  'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df[2:4]) # 这里选择第 3 到 第 4 行,与 Python 切片一致,不需要函数,直接切片即可

运行结果:

one  two
c  3.0    3
d  NaN    4

2.2 增加行(append 函数)

# 通过 append 函数
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

df = df.append(df2)
print(df) # 这里相当于把 第二个 dataframe 与第一个进行拼接,默认的 index 都是 0 1
print(df.loc[0]) # 这里有两行的 index 是 0

运行结果:

a  b
0  1  2
1  3  4
0  5  6
1  7  8
   a  b
0  1  2
0  5  6

2.3 删除行(drop 函数)

# 通过 drop 函数
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

df = df.append(df2)

df = df.drop(0) # 这里有两个行标签为 0,所以直接删除了 2 行
print(df)

运行结果:

a  b
1  3  4
1  7  8

到此这篇关于Python Pandas 对列/行进行选择,增加,删除操作的文章就介绍到这了,更多相关Python Pandas行列选择增加删除内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python pandas库中DataFrame对行和列的操作实例讲解

    用pandas中的DataFrame时选取行或列: import numpy as np import pandas as pd from pandas import Sereis, DataFrame ser = Series(np.arange(3.)) data = DataFrame(np.arange(16).reshape(4,4),index=list('abcd'),columns=list('wxyz')) data['w'] #选择表格中的'w'列,使用类字典属性,返回的是S

  • python时间日期函数与利用pandas进行时间序列处理详解

    python标准库包含于日期(date)和时间(time)数据的数据类型,datetime.time以及calendar模块会被经常用到. datetime以毫秒形式存储日期和时间,datetime.timedelta表示两个datetime对象之间的时间差. 下面我们先简单的了解下python日期和时间数据类型及工具 给datetime对象加上或减去一个或多个timedelta,会产生一个新的对象 from datetime import datetime from datetime impo

  • Python Pandas 获取列匹配特定值的行的索引问题

    给定一个带有列"BoolCol"的DataFrame,如何找到满足条件"BoolCol" == True的DataFrame的索引 目前有迭代的方式来做到这一点: for i in range(100,3000): if df.iloc[i]['BoolCol']== True: print i,df.iloc[i]['BoolCol'] 这虽然可行,但不是标准的 Pandas 方式.经过一番研究,我目前正在使用这个代码: df[df['BoolCol'] == T

  • python pandas获取csv指定行 列的操作方法

    pandas获取csv指定行,列 house_info = pd.read_csv('house_info.csv') 1:取行的操作: house_info.loc[3:6]类似于python的切片操作 2:取列操作: house_info['price']  这是读取csv文件时默认的第一行索引 3:取两列 house_info[['price',tradetypename']] 取多个列也是同理的,注意里面是一个list的列表,不然会报错误: 4:增加列: house_Info['adre

  • python pandas dataframe 按列或者按行合并的方法

    concat 与其说是连接,更准确的说是拼接.就是把两个表直接合在一起.于是有一个突出的问题,是横向拼接还是纵向拼接,所以concat 函数的关键参数是axis . 函数的具体参数是: concat(objs,axis=0,join='outer',join_axes=None,ignore_index=False,keys=None,levels=None,names=None,verigy_integrity=False) objs 是需要拼接的对象集合,一般为列表或者字典 axis=0 是

  • python pandas dataframe 行列选择,切片操作方法

    SQL中的select是根据列的名称来选取:Pandas则更为灵活,不但可根据列名称选取,还可以根据列所在的position(数字,在第几行第几列,注意pandas行列的position是从0开始)选取.相关函数如下: 1)loc,基于列label,可选取特定行(根据行index): 2)iloc,基于行/列的position: 3)at,根据指定行index及列label,快速定位DataFrame的元素: 4)iat,与at类似,不同的是根据position来定位的: 5)ix,为loc与i

  • Python Pandas中根据列的值选取多行数据

    Pandas中根据列的值选取多行数据 # 选取等于某些值的行记录 用 == df.loc[df['column_name'] == some_value] # 选取某列是否是某一类型的数值 用 isin df.loc[df['column_name'].isin(some_values)] # 多种条件的选取 用 & df.loc[(df['column'] == some_value) & df['other_column'].isin(some_values)] # 选取不等于某些值的

  • Python Pandas 对列/行进行选择,增加,删除操作

    一.列操作 1.1 选择列 d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) print (df ['one']) # 选择其中一列进行显示,列长度为最长列的长度 # 除了 index 和 数据,还会显示 列表头名,和 数据 类型 运行结果: a    1.0 b   

  • python pandas修改列属性的方法详解

    使用astype如下: df[[column]] = df[[column]].astype(type) type即int.float等类型. 示例: import pandas as pd data = pd.DataFrame([[1, "2"], [2, "2"]]) data.columns = ["one", "two"] print(data) # 当前类型 print("----\n修改前类型:&quo

  • Python pandas 计算每行的增长率与累计增长率

    读取数据: FacebookDf=pd.read_excel(r'D:\jupyter\Untitled Folder\Facebook2017年股票数据.xlsx',index_col='Date') FacebookDf.tail() 计算当前行比上一行增长的百分比(每行的增长率) # .pct_change()返回变化百分比,第一行因没有可对比的,返回Nan,填充为0 # apply(lambda x: format(x, '.2%'))将小数点转换为百分数 FacebookDf['pct

  • python pandas遍历每行并累加进行条件过滤方式

    目录 pandas遍历每行并累加进行条件过滤 python DataFrame遍历 1.DataFrame.iterrows() 2.DataFrame.itertuples() 3.DataFrame.iteritems() pandas遍历每行并累加进行条件过滤 本次记录主要实现对每行进行排序,并保留前80%以前的偏好. 思路: 将每行的概率进行排序,然后累加,累加值小于等于0.8的偏好保留,获得一个累加过滤的dataframe,然后映射回原始数据中,保留每行的偏好.接下来是代码的实现 a

  • 给jqGrid数据行添加修改和删除操作链接(之一)

    我这里用的不是jqGrid的自带的编辑和删除操作,我已经把分页导航栏下的编辑,删除,搜索都取消掉了,就是这句$("#list1").navGrid("#pager1",{edit:false,del:false, search:false}), 然后在数据加载完成后,给每行添加了 修改和删除链接 jqGrid完成的事件是gridComplete:function(){}(可以理解为数据都准备好了), 因为从数据库获取到的json数据没有带修改和删除两项,所以在之后的

  • python pandas库读取excel/csv中指定行或列数据

    目录 引言 1.根据index查询 2.已知数据在第几行找到想要的数据 3.根据条件查询找到指定行数据 4.找出指定列 5.找出指定的行和指定的列 6.在规定范围内找出符合条件的数据 总结 引言 关键!!!!使用loc函数来查找. 话不多说,直接演示: 有以下名为try.xlsx表: 1.根据index查询 条件:首先导入的数据必须的有index 或者自己添加吧,方法简单,读取excel文件时直接加index_col 代码示例: import pandas as pd #导入pandas库 ex

随机推荐