Mar*_*ico 5 python arrays series dataframe pandas
我有以下问题:我有一个这样的数据框:
col1 col2 col3
0 2 5 4
1 4 3 5
2 6 2 7
Run Code Online (Sandbox Code Playgroud)
现在我有一个数组,例如 a = [5,5,5] 并且我想在 col3 中插入这个数组,但只在特定的行(比如 0 和 2)中插入并获得类似的东西:
col1 col2 col3
0 2 5 [5,5,5]
1 4 3 5
2 6 2 [5,5,5]
Run Code Online (Sandbox Code Playgroud)
问题是,当我尝试这样做时:
zip_df.at[[0,2],'col3'] = a
Run Code Online (Sandbox Code Playgroud)
我收到以下错误ValueError: Must have equal len keys and value when setting with an ndarray。我怎么解决这个问题?
不推荐您尝试的操作。1 Pandas 的设计目的不是为了串联列表。话虽如此,您可以明确定义一个系列并通过update或 进行分配loc。Noteat仅用于获取或设置单个值,而不是像您的情况那样获取或设置多个值。
a = [5, 5, 5]
indices = [0, 2]
df['col3'].update(pd.Series([a]*len(indices), index=indices))
# alternative:
# df.loc[indices, 'col3'] = pd.Series([a]*len(indices), index=indices)
print(df)
col1 col2 col3
0 2 5 [5, 5, 5]
1 4 3 5
2 6 2 [5, 5, 5]
Run Code Online (Sandbox Code Playgroud)
1更多信息(来源):
不要这样做。Pandas 从未被设计为在系列/列中保存列表。您可以编造昂贵的解决方法,但不推荐使用这些方法。
不推荐连续保存列表的主要原因是您失去了使用连续内存块中保存的 NumPy 数组的矢量化功能。你的系列将是
objectdtype,它代表一个指针序列,很像list. 您将失去内存和性能方面的优势,以及对优化 Pandas 方法的访问。另请参阅NumPy 相对于常规 Python 列表的优势是什么? 支持 Pandas 的论据与支持 NumPy 的论据相同。