如何将元素追加到DataFrame内部的列表中? [英] How to append an element to a List inside a DataFrame?
问题描述
假设我有一个列表的数据框,
Suppose I have a DataFrame of lists,
my_df = pd.DataFrame({'my_list':[[45,12,23],[20,46,78],[45,30,45]]})
会产生以下结果:
my_list
0 [45, 12, 23]
1 [20, 46, 78]
2 [45, 30, 45]
我如何在每行 my_list
中添加一个元素,例如99吗?
How can I add an element, let's say 99, to my_list
for each row ?
预期结果:
my_list
0 [45, 12, 23, 99]
1 [20, 46, 78, 99]
2 [45, 30, 45, 99]
推荐答案
听起来很无聊,但直接遍历值-这样您就可以调用 append
并避免使用 + =
进行任何重新绑定,从而使处理速度大大提高。
Sounds awfully boring but just iterate over the values directly - this way you can call append
and avoid whatever rebinding occurs with +=
, making things significantly faster.
for val in my_df.my_list:
val.append(99)
演示
>>> import timeit
>>> setup = '''
import pandas as pd; import numpy as np
df = pd.DataFrame({'my_list': np.random.randint(0, 100, (500, 500)).tolist()})
'''
>>> min(timeit.Timer('for val in df.my_list: val.append(90)',
setup=setup).repeat(10, 1000))
0.05669815401779488
>>> min(timeit.Timer('df.my_list += [90]',
setup=setup).repeat(10, 1000))
2.7741127769695595
当然,如果速度(或什至不是速度)对您很重要,您应该问自己是否确实需要在DataFrame中具有列表。考虑使用NumPy数组,直到需要Pandas实用程序并执行
Of course, if speed (or even if not speed) is important to you, you should question if you really need to have lists inside a DataFrame. Consider working on a NumPy array until you need Pandas utility and doing something like
np.c_[arr, np.full(arr.shape[0], 90)]
或至少将DataFrame中的列表拆分为单独的列并分配一个新列。
or at least splitting your lists inside the DataFrame to separate columns and assigning a new column .
这篇关于如何将元素追加到DataFrame内部的列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!