簡體   English   中英

查找數據框列中的元素數

[英]find the number of elements in a column of a dataframe

我想從數據框中歸檔一列的行長。

數據框名稱- df

sample data:
a   b   c
1   d   ['as','the','is','are','we']
2   v   ['a','an']
3   t   ['we','will','pull','this','together','.']

expected result:
a   b   c                                          len
1   d   ['as','the','is','are','we']               5
2   v   ['a','an']                                 2
3   t   ['we','will','pull','this','together','.'] 6

到目前為止,我剛剛嘗試過:

df.loc[:,'len']=len(df.c)

但這給了我數據框中存在的總行數。 如何獲取數據框特定列的每一行中的元素?

一種方法是使用apply並計算 len

In [100]: dff
Out[100]:
   a  b                                    c
0  1  d               [as, the, is, are, we]
1  2  v                              [a, an]
2  3  t  [we, will, pull, this, together, .]

In [101]: dff['len'] = dff['c'].apply(len)

In [102]: dff
Out[102]:
   a  b                                    c  len
0  1  d               [as, the, is, are, we]    5
1  2  v                              [a, an]    2
2  3  t  [we, will, pull, this, together, .]    6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM