通过计算另一列的长度将列添加到pandas中的数据帧

时间:2016-03-04 12:35:37

标签: python pandas

我有一个数据框,其中第一个coloumn有名字。现在我想将该字符串的长度添加为dataframe中的第二个coloumn

list = ["apple","mango","banana","orange"]
df=pd.DataFrame(list)

是dataframe的代码,例如...... 我希望数据框为

        0  len
0   apple    5
1   mango    5
2   banana   6
3   ora      3

1 个答案:

答案 0 :(得分:0)

您可以使用str.len

import pandas as pd


list = ["apple","mango","banana","orange"]
df=pd.DataFrame(list)

df['len'] = df.iloc[:,0].str.len()
print df
        0  len
0   apple    5
1   mango    5
2  banana    6
3  orange    6

或者:

list = ["apple","mango","banana","orange"]
df=pd.DataFrame(list, columns=['a'])

df['len'] = df['a'].str.len()
print df
        a  len
0   apple    5
1   mango    5
2  banana    6
3  orange    6