我有这张数据df
name class
1 Bob history
2 Chuck math
3 Daren history
4 Elisa english
5 Aaron history
6 Tom math
7 Dan history
8 Fred english我想同时创建两个新列(),,这是现有两列的字符长度。结果应该如下所示:
name class name_len class_len
1 Bob history 3 7
2 Chuck math 5 4
3 Daren history 5 7
4 Elisa art 5 3
5 Aaron history 5 7
6 Tom math 3 4
7 Dan history 3 7
8 Fred business 4 8我曾尝试使用“理解”一次生成列表,如下所示:
df[["1", "2"]] = [df[name].apply(len) for name in posts.columns]但我得到
ValueError: Columns must be same length as key我想做更复杂的操作,并从预先存在的列中创建许多新列,并且不希望手动创建每个新列一次。任何帮助都是非常感谢的!
发布于 2022-10-02 20:25:47
不需要使用apply,.str.len()应该工作:
for col in df.columns:
df[f"{col}_len"] = df[col].str.len()
df
name class name_len class_len
1 Bob history 3 7
2 Chuck math 5 4
3 Daren history 5 7
4 Elisa english 5 7
5 Aaron history 5 7
6 Tom math 3 4
7 Dan history 3 7
8 Fred english 4 7https://stackoverflow.com/questions/73929073
复制相似问题