lundi 19 octobre 2020

Pandas Python splitting a row , using it to count how many times it appears and replacing the results

Suppose a data frame with 3 columns looks like this:

.    Values  Objects     Legs

0     1        568        25
1     5        387        56
2     0        526        52
3     3        982        89
4     0        098        09
5     8        697        89
6     0        647        01

I want to create code that says if row(Values) == 0, split corresponding row(objects).str[2] and use the split number to count how many times it appears in Legs column and then create a dataframe with the results. Rows that are not zero should be left as they are. I have the following code but returns error Str has no str attribute

#
import panda as pd
df = pd.read_csv('Hello world')

#Making index loop for every 'Values' row
for index in df.index:

   #checking for zero 
   if df.loc[index,'Values'] == 0.0:
   
   #Splitting the 'Objects' row and counting how many times the split str in the 'Legs' Column when true
   df.loc[df.Legs == df.loc[0,'Objects'].astype(str).str[2], 'Legs'].count()

Expected output

.    Values  Objects     Legs   Counts

0     1        568        25      
1     5        387        56
2     0        526        52      1         #Counted 52 in 'Legs'
3     3        982        89
4     0        098        09      1         #Counted 09 in  'Legs' 
5     8        697        89
6     0        647        01      0         #Counted 64 in 'Legs'

Aucun commentaire:

Enregistrer un commentaire