最近做一个系列博客,跟着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. 通过map文件了解堆栈分配(STM32、MDK5)--避免堆栈溢出

    环境:STM32F103C8T6,MDK5 在最近的一个项目的开发中,每当调用到一个函数,程序就直接跑飞.debug跟进去看不出什么逻辑错误,但发现函数内局部变量声明之后,全局变量的值被清零,后来查看 ...

  2. CentOS 7配置静态IP地址

    [root@centos1 ~]# ifconfig -bash: ifconfig: command not found 首先,习惯性的输入echo $PATH(查看当前PATH环境变量,跟DOS的 ...

  3. ThinkPHP将上传问件添加到数据库

    <?php namespace Home\Controller; /***************** use Think\Controller; ****命名空间****/ class Mes ...

  4. 推荐一个快速了解移植uboot以及linux到新板子上的ppt教程

    链接地址在此: https://elinux.org/images/2/2a/Schulz-how-to-support-new-board-u-boot-linux.pdf

  5. openwrt设置uboot环境变量在flash上的存储地址

    1.分析如下 ubootenv_add_app_config ubootenv_add_uci_config "/dev/mtd1" "0x40000" &qu ...

  6. 解题报告:51nod 加农炮

    2017-10-07 16:15:16 writer:pprp 题目来源: Codility 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题   一个长度为M的正整 ...

  7. 几种创建XMLHttpRequest对象的方法

    XMLHttpRequest对象,也就是Ajax交互的核心对象. 这里列举三种创建Ajax对象的方法. 第一种: <!DOCTYPE html> <html> <head ...

  8. LA 5846 霓虹灯广告牌(单色三角形问题)

    https://vjudge.net/problem/UVALive-5846 题意: 圆周上有n个点,两两相连,只能涂红色或蓝色.求单色三角形的个数. 思路: 这个问题在训练指南105页有详细讲解. ...

  9. Extjs的form跨域提交文件时,无法获取返回结果

    form文件表单跨域提交时,无法获取远程服务器的返回结果,form提交代码如下: form.submit({ url:'http://{remoteUrl}/hgisserver/wrds/file' ...

  10. 经典C#面试题

    1.在下面的代码中,如何引用命名空间fabulous中的great? namespace fabulous{// code in fabulous namespace}namespace super{ ...