python - 如何覆盖 pandas DataFrame 中的数组单元格?

标签 python pandas dataframe

有以下数据框:

df = pd.DataFrame({
    'ID': [1,2,3],
    'Name': ['abc', 'jkl', 'qwe'],
    'Array': [[1,2,3], [10,11,12], [4,5,4]]
})

    ID  Name    Array
0   1   abc [1, 2, 3]
1   2   jkl [10, 11, 12]
2   3   qwe [4, 5, 4]

现在我不想将 df['Name']=='qwe' 的数组覆盖为 [17,23,5]。 正确的输出如下所示:

    ID  Name    Array
0   1   abc [1, 2, 3]
1   2   jkl [10, 11, 12]
2   3   qwe [17, 23, 5] 

我的想法:

df.loc[df['Name']=='qwe', 'Array'] = [17,23,5]
-> ValueError: Must have equal len keys and value when setting with an iterable

df.loc[df['Name']=='qwe', 'Array'] = [[17,23,5]]
-> ValueError: Must have equal len keys and value when setting with an ndarray

df.loc[df['Name']=='qwe', 'Array'] = np.array([17,23,5])
-> ValueError: Must have equal len keys and value when setting with an iterable

df.loc[df['Name']=='qwe', 'Array'] = pd.DataFrame({'Array':[[17,23,5]]})
->  ID  Name    Array
0   1   abc [1, 2, 3]
1   2   jkl [10, 11, 12]
2   3   qwe NaN

有没有简单的方法可以解决这个问题?提前致谢。

最佳答案

使用掩码过滤索引值创建系列:

df = pd.DataFrame({
    'ID': [1,2,3],
    'Name': ['abc', 'qwe', 'qwe'],
    'Array': [[1,2,3], [10,11,12], [4,5,4]]
})

m = df['Name']=='qwe'
df.loc[m, 'Array'] =  pd.Series([[17,23,5]] * m.sum(), index=df.index[m])

print (df)
   ID Name        Array
0   1  abc    [1, 2, 3]
1   2  qwe  [17, 23, 5]
2   3  qwe  [17, 23, 5]

关于python - 如何覆盖 pandas DataFrame 中的数组单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71379089/

相关文章:

python 什么时候调用 logging.Handler flush-method?

pandas - 计算数据框中特定列中的 NaN

python - 如何计算任何 datetime64 列的第二天分钟差?

python - 以数据帧格式打印列表

python - 使用python删除excel文件中的NA行

python - 如何在 Pandas DataFrame 中获取符合条件的唯一值?

python - 按条件删除行并填充 pandas 数据框中的新列

python - 使用 pandas df 旋转 sns 热图

python - 使用大小不匹配的python合并两个excel文件

python - 值错误 : I/O operation on closed file with python cStringIO