gpt4 book ai didi

python - 计算一行中的字符数作为新列

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:35 24 4
gpt4 key购买 nike

我有一个大约有 100 列的 pandas 数据框,我想计算一行中每列中的字符数。

在 Excel 中,我会做类似 (Len(Concat(A2:CA2))

df['newcolumn'] = ? in Pandas Python

最佳答案

如有必要,首先将列转换为字符串,求和 以进行连接并最后使用 Series.str.len :

df['new'] = df.astype(str).sum(axis=1).str.len()

如果需要按位置选择列:

df['new'] = df.iloc[:, 1:20].astype(str).sum(axis=1).str.len()

如果只需要字符串列,请使用 DataFrame.select_dtypes :

df['new'] = df.select_dtypes(object).sum(axis=1).str.len()

关于python - 计算一行中的字符数作为新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56968917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com