I have a dataframe that looks something like this
Detail
--------------
0 Animal: Lion,
Weight: 600 kg,
Class: Mammal
1 Animal: Monkey,
Weight: 10 kg,
2 Animal: Snake,
Class: Reptile
3 Animal: Frog,
Class: Amphibian,
Weight: 1 kg
4 Animal: Hawk,
Class: Bird
I need to read each row to see if a particular string is present in each line, then strip the line and add it to a list. If the value is not present, I need it to be appended with a null value. Then, I want to export this list as a csv file.
My desired output here is
Animal
--------------
0 Animal: Lion,
1 Animal: Monkey,
2 Animal: Snake,
3 Animal: Frog,
4 Animal: Hawk,
Weight
--------------
0 Weight: 600 kg,
1 Weight: 10 kg,
2 Weight: NaN
3 Weight: 1 kg,
4 Weight: NaN
Class
--------------
0 Class: Mammal,
1 Class: NaN
2 Class: Reptile
3 Class: Amphibian
4 Class: NaN
I need these 3 dataframes to be exported as a csv file.
I have written something like this, but don't think it is the right approach
cols= ['Animal','Weight','Class']
for entry in cols:
values=[]
for content in df['Detail']:
if(df['Detail'].str.contains(entry)):
var=content.str.split('\n')
else:
var= np.nan
values.append(var)
values_df = pd.DataFrame(values)
values_df.to_csv('%s.csv' %entry,header=entry,index=False)