最近做一个系列博客,跟着stackoverflow学Pandas。

以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序:

https://stackoverflow.com/questions/tagged/pandas?sort=votes&pageSize=15

add one row in a pandas.DataFrame -DataFrame添加行

https://stackoverflow.com/questions/10715965/add-one-row-in-a-pandas-dataframe

不得不说,这个问题在stackoverflow有10个回答,303 votes,339k views但是最终没有得出一个比较好的答案。

下面例举几个可以实现的操作

loc、iloc

df = DataFrame(columns=('lib', 'qty1', 'qty2'))
for i in range(5):
    df.loc[i] = [randint(-1,1) for n in range(3)]
    # loc可以对没有的 index 进行赋值,而 iloc 则不允许,iloc只能对已经存在的位置进行操作。

print(df)

#     lib  qty1  qty2
# 0    0     0    -1
# 1   -1    -1     1
# 2    1    -1     1
# 3    0     0     0
# 4    1    -1    -1

这是一种方法,但是如果我们是往已有的DataFrame中添加数据,而已有的DataFrame已经存在相同的index就会造成替换。

当然如果我们对我们的数据足够了解,或者index并不重要,我们可以对index按0-based重新赋值。然后添加新行,也就不会出现问题。

append

我个人比较喜欢采用append函数,进行叠加,可以避免上面提到的相同index造成的替换问题。

可以参考:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html

import pandas as pd
from numpy.random import randint
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
for i in xrange(5):
    s = pd.Series({'lib':randint(-1,1), 'qty1':randint(-1,1), 'qty2':randint(-1,1)})
    # 这里 Series 必须是 dict-like 类型
    df = df.append(s, ignore_index=True)
# 这里必须选择ignore_index=True 或者给 Series 一个index值

时间测评

import time

import pandas as pd
from numpy.random import randint

# 采用 loc
t = time.time()
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
for i in xrange(10000):
     df.loc[i] = [randint(-1,1) for n in range(3)]
print('loc:', time.time() - t)

# 采用 append
t = time.time()
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
for i in xrange(10000):
    s = pd.Series({'lib':randint(-1,1), 'qty1':randint(-1,1), 'qty2':randint(-1,1)})
    df = df.append(s, ignore_index=True)
print('apped:', time.time() - t)
# ('loc:', 18.150289058685303)
# ('apped:', 15.132553100585938)

可以看出,采用 apped 的方法速度上比较快,而且可以避免index的错误。

【跟着stackoverflow学Pandas】add one row in a pandas.DataFrame -DataFrame添加行的更多相关文章

  1. 【跟着stackoverflow学Pandas】How to iterate over rows in a DataFrame in Pandas-DataFrame按行迭代

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  2. 【跟着stackoverflow学Pandas】 - Adding new column to existing DataFrame in Python pandas - Pandas 添加列

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  3. 【跟着stackoverflow学Pandas】 -Get list from pandas DataFrame column headers - Pandas 获取列名

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  4. 【跟着stackoverflow学Pandas】Select rows from a DataFrame based on values in a column -pandas 筛选

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  5. 【跟着stackoverflow学Pandas】“Large data” work flows using pandas-pandas大数据处理流程

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  6. 【跟着stackoverflow学Pandas】Delete column from pandas DataFrame-删除列

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  7. 【跟着stackoverflow学Pandas】Renaming columns in pandas-列的重命名

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

  8. [LeetCode] Add One Row to Tree 二叉树中增加一行

    Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value ...

  9. [Swift]LeetCode623. 在二叉树中增加一行 | Add One Row to Tree

    Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value ...

随机推荐

  1. CMake入门教程(转帖)

    本文转自:https://www.cnblogs.com/never--more/p/6921837.html CMake入门教程 参考文献:http://www.ibm.com/developerw ...

  2. MR案例:链式ChainMapper

    类似于Linux管道重定向机制,前一个Map的输出直接作为下一个Map的输入,形成一个流水线.设想这样一个场景:在Map阶段,数据经过mapper01和mapper02处理:在Reduce阶段,数据经 ...

  3. 终极之shell-zsh全解析

    什么是Zsh Zsh是一款强大的虚拟终端,既是一个系统的虚拟终端,也可以作为一个脚本语言的交互解析器. Zsh的一些特性 兼容bash,原来使用bash的兄弟切换过来毫无压力. 强大的历史纪录功能,在 ...

  4. centos 查询mysql配置文件位置

    具体指令: 1.which mysqld  (”which 文件名“ : 搜索命令所在路径及别名) 2./usr/sbin/mysqld --verbose --help | grep -A 1 'D ...

  5. Union 和Union all的区别

    Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序: Union All:对两个结果集进行并集操作,包括重复行,不进行排序: 例如: select employee_id,jo ...

  6. Flask-最简单的Python http服务框架使用

    环境准备 Python + pip + Flask sudo easy_install pip sudo pip install flask 代码如下(做了个jieba分词的服务) # encodin ...

  7. 【Network architecture】Rethinking the Inception Architecture for Computer Vision(inception-v3)论文解析

    目录 0. paper link 1. Overview 2. Four General Design Principles 3. Factorizing Convolutions with Larg ...

  8. Vjudge - B - 这是测试你会不会排序

    2017-07-14 22:44:11 writer:pprp 题目: 他们提出的比赛规则是这样的: 1.  每方派出n个人参赛: 2.  出赛的顺序必须是从弱到强(主要担心中国人擅长的田忌赛马):  ...

  9. jquery tmpl模板

    之前用模板渲染都是用angular,无意间发现了jquery tmpl这种轻量级,其文档在这里 官方解释对该插件的说明:将匹配的第一个元素作为模板,render指定的数据,签名如下: .tmpl([d ...

  10. SQL SERVER连接池

    Connection Pool 是什么呢 ?每当程序需要读写数据库的时候.Connection.Open()会使用ConnectionString连接到数据库,数据库会为程序建立 一个连接,并且保持打 ...