最近做一个系列博客,跟着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. web.xml filter配置

    filter介绍: filter主要用于对用户请求request进行预处理,和对Response进行后处理,是个典型的处理链. 详细解析起来就是:Filter对用户请求进行预处理,接着将请求HttpS ...

  2. 20145335郝昊《java程序设计》第9周学习总结

    20145335郝昊 <Java程序设计>第9周学习总结 教材学习内容总结 第16章 JDBC(Java DataBase Connectivity)即java数据库连接,是一种用于执行S ...

  3. MySQL优化具体

    1. 查询与索引优化分析 在优化MySQL时,通常需要对数据库进行分析,常见的分析手段有慢查询日志,profiling分析,EXPLAIN分析查询,以及show命令查询系统状态及系统变量,通过定位分析 ...

  4. Tomcat热部署,Web工程中线程没有终止

    近期项目中,用 jenkins 热部署 web工程时,发现工程中静态持有的线程(将ScheduledExecutorService定时任务存储在静态Map中),导致不定时出现数据库访问事务关闭异常,如 ...

  5. Elasticsearch Server,2nd Edition pdf 翻译 中文

    很偶然的机会,就需要接触到搜索,入门就是google trend已然超过solr的ES.在入门的时候找书的时候发现没有中文版的.于是自己开始翻译Elasticsearch Server,2nd Edi ...

  6. LeetCode——Longest Repeating Character Replacement

    1. Question Given a string that consists of only uppercase English letters, you can replace any lett ...

  7. LeetCode——remove-duplicates-from-sorted-list-ii

    Question Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only dist ...

  8. C#(Wpf)实现小键盘

    花了一天时间小键盘基本功能已完成,先看看效果图吧! 默认: Shift: Caps Lock: Button style <Style x:Key="KeyButton" T ...

  9. jQuery Ajax总结

    jQuery对Ajax的操作进行了封装.jQuery中\(.ajax()属于最底层的方法,这个放在后面说,首先看看封装了\).ajax()的方法. load()方法 load()可以远程载入HTML并 ...

  10. mysql 索引相关问题

    mysql中key .primary key .unique key 与index区别 https://blog.csdn.net/nanamasuda/article/details/5254317 ...