相关文章推荐
旅途中的牛腩  ·  python ...·  3 周前    · 
绅士的创口贴  ·  震惊! ...·  1 周前    · 
被表白的橙子  ·  使用Python ...·  1 周前    · 
有胆有识的开心果  ·  Android studio ...·  2 年前    · 
成熟的春卷  ·  硬核技术干货 | ...·  2 年前    · 
本文介绍了如何使用Pandas库进行DataFrame的基本操作,包括获取行数和列数、访问索引和元素值,以及增删行、列、行和列的实例。通过详细步骤展示了数据的插入、删除和重新排列技巧,适合初学者理解DataFrame操作核心。 摘要生成于 ,由 DeepSeek-R1 满血版支持,

一、获取行数、列数

>>> df = pd.DataFrame(np.arange(12).reshape(3, 4), index = ['row1', 'row2', 'row3'], columns=['col1', 'col2', 'col3', 'col4'])
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
# 获取行数
>>> df.shape[0]
>>> len(df)
>>> df.iloc[:,0].size
# 获取列数
>>> df.shape[1]
>>> df.columns.size

二、获取索引、元素值

>>> df = pd.DataFrame(np.arange(12).reshape(3, 4), index = ['row1', 'row2', 'row3'], columns=['col1', 'col2', 'col3', 'col4'])
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
# 获取索引
>>> df.ix[[0]].index.values[0]
'row1'
# 获取元素,0行0列
>>> df.ix[[0]].values[0][0]
# 获取元素,0行1列
>>> df.ix[[0]].values[0][1]

三、增加行、列

>>> df = pd.DataFrame(np.arange(12).reshape(3, 4), index = ['row1', 'row2', 'row3'], columns=['col1', 'col2', 'col3', 'col4'])
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
# 增加行
>>> df.loc['row4']=[12,13,14,15]
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
row4    12    13    14    15
# 增加列
>>> df['col5']=[11,22,33,44]
      col1  col2  col3  col4  col5
row1     0     1     2     3    11
row2     4     5     6     7    22
row3     8     9    10    11    33
row4    12    13    14    15    44

四、删除行、列

>>> df = pd.DataFrame(np.arange(12).reshape(3, 4), index = ['row1', 'row2', 'row3'], columns=['col1', 'col2', 'col3', 'col4'])
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
# 删除行
>>> df.drop(['row1'], axis=0)
      col1  col2  col3  col4
row2     4     5     6     7
row3     8     9    10    11
# 删除列
>>> df.drop(['col4'], axis=1)
      col1  col2  col3
row1     0     1     2
row2     4     5     6
row3     8     9    10

按条件删除行、列的方法:

# 删除dataframe的id大于100且小于200的所有行
df = df.drop(df[(df.id > 100) & (df.id < 200)].index)
# 删除dataframe的name列
df = df.drop('name', axis=1)

五、插入行、列

>>> df = pd.DataFrame(np.arange(12).reshape(3, 4), index = ['row1', 'row2', 'row3'], columns=['col1', 'col2', 'col3', 'col4'])
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
# 插入列
>>> df.insert(2,'col_insert',[11,22,33])
      col1  col2  col_insert  col3  col4
row1     0     1          11     2     3
row2     4     5          22     6     7
row3     8     9          33    10    11
>>> df = pd.DataFrame(np.arange(12).reshape(3, 4), index = ['row1', 'row2', 'row3'], columns=['col1', 'col2', 'col3', 'col4'])
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
# 先插入行在最后
>>> df.loc['row12']=[11,22,33,44]
       col1  col2  col3  col4
row1      0     1     2     3
row2      4     5     6     7
row3      8     9    10    11
row12    11    22    33    44
# 然后插入行序号
>>> df['rowindex']=[1,3,4,2]
       col1  col2  col3  col4  rowindex
row1      0     1     2     3         1
row2      4     5     6     7         3
row3      8     9    10    11         4
row12    11    22    33    44         2
# 再按行号排序,得到结果 
>>> df=df.sort_values(by='rowindex')
       col1  col2  col3  col4  rowindex
row1      0     1     2     3         1
row12    11    22    33    44         2
row2      4     5     6     7         3
row3      8     9    10    11         4

六、append方法添加行

DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=False)

【1】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html

【2】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html

【3】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

df=DataFrame([{‘A’:’11’,’B’:’12’},{‘A’:’111’,’B’:’121’},{‘A’:’1111’,’B’:’1211’}])print df.columns.size#列数 2 print df.iloc[:,0].size#行数 3 print df.ix[[0]].index.values[0]#索引 0 print df.ix[[0]].valu
Python茴香豆系列】之 PANDAS 获取 DataFrame行数Python 编程,使用不同的方法来完成同一个目标,有时候是一件很有意思的事情。这让我想起鲁迅笔下的孔乙己。孔乙己对于茴香豆的茴字的四种写法颇有研究。我不敢自比孔乙己,这里搜集一些 Python 的茴香豆,以飨各位码农。 一共有多少条数据?这大概是数据分析工作最基本的内容吧。 这里,我们来聊一聊如何获取 PandasDataFrame行数。 首先准备一个用于测试的 DataFrame 。这个 DataFrame
import pandas as pd df = pd.DataFrame({'Country':['China','China', 'India', 'India', 'America', 'Japan', 'China', 'India'], 'Income':[10000, 10000, 5000, 5002, 40000, 50000, 8000, 5000], 'Number':[5000, 4321, 1234,
#### 方法一:使用 `len()` 函数 `len()` 是 Python 内置函数之一,可以直接作用于 DataFrame 对象以返回其行数[^3]。 ```python row_count = len(df) print(row_count) #### 方法二:利用 `.shape` 属性 `.shape` 返回的是一个包含两个元素的元组 (rows, columns),其中第一个元素表示行数,第二个元素表示列数[^2]。因此可以通过索引来提取行数: ```python row_count = df.shape[0] print(row_count) #### 方法三:基于索引长度计算 通过访问 DataFrame索引属性 (`df.index`) 并对其应用 `len()` 函数也可以得出总行数[^3]: ```python row_count = len(df.index) print(row_count) 以上三种方法均能有效统计给定 DataFrame 的实际行数量。 ### 示例代码综合展示 下面给出一段完整的示例程序,演示前述提到的不同技术手段来取得相同的结果——即目标 DataFrame行数目: ```python import pandas as pd import numpy as np # 创建测试用DataFrame df = pd.DataFrame({'a': [None, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}) print("原始数据:") print(df) # 使用不同方法获取行数 method_one_result = len(df) method_two_result = df.shape[0] method_three_result = len(df.index) # 输出结果对比验证一致性 print(f"\nMethod One Result: {method_one_result}") print(f"Method Two Result: {method_two_result}") print(f"Method Three Result: {method_three_result}") assert method_one_result == method_two_result == method_three_result, "各方法所得行数不一致" (Keras)ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int/float)错误 25685 (Keras)ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int/float)错误 qq_42863961: 我认为行不通~~