1

I want to replace objects with amount of objects in pandas Data Frame.

Data Frame looks like this:

      [IRN, PAK, TKM, UZB, TJK, CHN]  
                                  []  
                [MNE, GRC, MKD, KOS]  
 [TUN, LBY, NER, ESH, MRT, MLI, MAR]  
                                  []  
                          [FRA, ESP]  

I want to calculate objects in each rows and replace objects with amount to get something like this:

     [IRN, PAK, TKM, UZB, TJK, CHN]   6
                                 []   NaN
               [MNE, GRC, MKD, KOS]   4
[TUN, LBY, NER, ESH, MRT, MLI, MAR]   7
                                 []   NaN
                         [FRA, ESP]   2
BohdanS
  • 111
  • 1
  • 8

1 Answers1

0

In the most generic covention without knowing your column names:

df['Length'] = df.iloc[:,0].str.len().replace(0,np.nan)

Output:

                               Country  Length
0       [IRN, PAK, TKM, UZB, TJK, CHN]     6.0
1                                   []     NaN
2                 [MNE, GRC, MKD, KOS]     4.0
3  [TUN, LBY, NER, ESH, MRT, MLI, MAR]     7.0
4                                   []     NaN
5                           [FRA, ESP]     2.0
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • Thanks for answer. It puts "2" everywhere instead of objects and shows SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead – BohdanS Jun 09 '17 at 21:46
  • Is that a string dtype? or a list? – Scott Boston Jun 09 '17 at 21:51
  • It's dtype: object. I tried again and it works but shows the same Warning. – BohdanS Jun 09 '17 at 22:11
  • Yes the setting warnng means that it will not change your original dataframe. Inorder to get around this... Need to use .copy when creating this dataframe. See the comments in this [SO Post](https://stackoverflow.com/questions/44466332/pythonic-way-to-set-entire-column-to-value-pandas-settingwithcopywarning). – Scott Boston Jun 09 '17 at 22:15
  • 1
    I made a copy and it works without a warning. Thank you very much! – BohdanS Jun 09 '17 at 22:22