简体   繁体   English

Python:使用 len() 根据其他列的值创建新列

[英]Python: Create New Column based on values of other column using len()

My dataframe is a pandas dataframe df with many rows & columns.我的 dataframe 是一个 pandas dataframe df,有很多行和列。 Now i want to create a new column (series) based on the values of an object column.现在我想根据 object 列的值创建一个新列(系列)。 eg:例如:

df.iloc[0, 'oldcolumn'] Output is 0 should give me 0 in a new column and df.iloc[0, 'oldcolumn'] Output is 0 应该在新列中给我0并且

df.iloc[1, 'oldcolumn'] Output is 'ab%$.' df.iloc[1, 'oldcolumn'] Output 是 'ab%$'。 should give me 5 in the same new column (number of literals incl. space).应该在同一个新列中给我5 (文字数量,包括空格)。

in addition, is there a way to avoid loops or own functions?另外,有没有办法避免循环或自己的功能? Thank U感谢你

To create a new column based on the length of the value in another column, you should do要根据另一列中值的长度创建新列,您应该这样做

df['newcol'] = df['oldcol'].apply(lambda x: len(str(x)))

Although this is a generic way of creating a new column based on data from existing columns, Henry's approach is also a good one.尽管这是基于现有列的数据创建新列的通用方法,但 Henry 的方法也是一种不错的方法。

In addition, is there a way to avoid loops or own functions?另外,有没有办法避免循环或者自带函数呢?

I recommend you take a look at How To Make Your Pandas Loop 71803 Times Faster .我建议您看看如何使 Pandas 循环 71803 倍更快

You can try this:你可以试试这个:

df['strlen'] = df['oldcolumn'].apply(len)
print(df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM