python - 访问 Pandas DataFrame 元素中的列表并对列表求和

标签 python pandas

我在数据框中有以下列:

columnA
[1.,2.3,3.]
[2]
[3,4.]

与本论坛中的其他帖子类似,我想在我的数据框中总结这种类型的列表,所以在这种情况下我想总结列表,我有新的专栏:

columnA
6.3
2
7

我试过: df['columnA'] = df5['columnA'].apply(lambda x: x.sum())给出错误:AttributeError: 'list' object has no attribute '总和'

我试过:df['columnA'] = (df['columnA'].values.tolist()).sum(1),它给出了同样的错误。

最佳答案

看起来您的列中也有 float 。使用 isinstance 检查对象是否可迭代,然后使用 sum

例如:

df = pd.DataFrame({'columnA':[[1.,2.3,3.], [2], [3,4.], 10.9]})
df["columnA"] = df["columnA"].apply(lambda x: sum(x) if isinstance(x, (list, tuple)) else x)
print(df)

输出:

   columnA
0      6.3
1      2.0
2      7.0
3     10.9

关于python - 访问 Pandas DataFrame 元素中的列表并对列表求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56753309/

相关文章:

python - 对于一对多数据库模型,如何编写 sqlite 查询以避免 python 中的循环?

python - 我怎样才能包含标题?

python - 在不知道行数的情况下,根据行数将数据框分成六等份 - pandas

python - pandas dataframes 将行合并为列

python - 如何在eager执行模式下获取keras模型的可训练变量?

python - 如何添加键值而不是替换它们。 Python 字典

python - python 中的 Bash 参数

python - ValueError : Units 'M' and 'Y' are no longer supported, 因为它们不代表明确的 timedelta 值持续时间

python - Pandas 数据框如何用多个替换单列

python - 获取 Pandas df中连续值为零的列的索引