python - 动态添加行到 DataFrame

标签 python pandas dataframe

假设我有一个空数据框,已经设置了列,但没有行。我正在从网络上抓取一些数据,所以假设我需要将索引 '2176' 添加到空数据框。当我尝试分配它时,如何自动将此行添加到数据库中?这甚至是 pandas 的目的还是我应该使用其他东西?

最佳答案

作为 .loc 的替代方案,您可能需要考虑 at .使用@NickBraunagel 的示例:

df = pd.DataFrame(columns=['foo1','foo2'])

然后

df.at['2716', 'foo1'] = 10

产量

     foo1 foo2
2716   10  NaN

时间完全不同:

# @NickBraunagel's solution
%timeit df.loc['2716', 'foo1'] = 10
1000 loops, best of 3: 212 µs per loop

# the at solution
%timeit df.at['2716', 'foo1'] = 10
100000 loops, best of 3: 12.5 µs per loop

如果你想同时添加多个列条目,你可以这样做:

d = {'foo1': 20, 'foo2': 10}
df.at['1234', :] = d

屈服

     foo1 foo2
2716   10  NaN
1234   20   10

但是,请确保始终添加相同的数据类型以避免错误或其他不良影响,如 here 所述。 .

关于python - 动态添加行到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030350/

相关文章:

java - Malt 解析器抛出类未找到异常

python - 获取 urllib2.urlopen 的 HTTP 返回值的套接字

python - 如何根据特定列表计算频率?

python - 如何将 UTC 时间戳字符串转换为 pandas 日期时间?

python - PySpark DataFrame - 动态加入多列

python - pandas 可以在不尝试将索引转换为周期的情况下绘制时间序列吗?

python - GAE : Is it necessary to call fetch on a query before getting its cursor?

python - 用另一列中的元素替换数据框中的列 - python

python - 值错误 : Wrong number of items passed - Meaning and suggestions?

python - 如何修复 Python Numpy/Pandas 安装?