如何在Pandas数据框的新列中添加值? [英] How to add values to a new column in pandas dataframe?
问题描述
我想在Pandas数据框中创建一个新的命名列,将第一个值插入其中,然后在同一列中添加另一个值:
I want to create a new named column in a Pandas dataframe, insert first value into it, and then add another values to the same column:
类似以下内容:
import pandas
df = pandas.DataFrame()
df['New column'].append('a')
df['New column'].append('b')
df['New column'].append('c')
etc.
我该怎么做?
推荐答案
不要这样做,因为速度慢:
6)一次更新一个空行。我已经看到这种方法使用了太多的方法。这是迄今为止最慢的。它可能很常见(对于某些python结构来说相当快),但是DataFrame对索引进行了大量检查,因此每次更新一行总是很慢。创建新结构和连接要好得多。
6) updating an empty frame a-single-row-at-a-time. I have seen this method used WAY too much. It is by far the slowest. It is probably common place (and reasonably fast for some python structures), but a DataFrame does a fair number of checks on indexing, so this will always be very slow to update a row at a time. Much better to create new structures and concat.
更好的方法是创建数据列表并创建 DataFrame
由建设者:
Better is create list of data and create DataFrame
by contructor:
vals = ['a','b','c']
df = pandas.DataFrame({'New column':vals})
这篇关于如何在Pandas数据框的新列中添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!