Search code examples
pythonpandastransformationcutcat

How can I update dataframe's columns after transformation?


I have the following dataframe

      age  sex   cp 
0    63.0  1.0  1.0
1    67.0  1.0  4.0
2    41.0  0.0  2.0

And I applied transformation process on each column as follows:

age = store_data['age']
age_bins = [0, 40, 60, 100]
age_categories = pd.cut(age, age_bins)

sex = store_data['sex']
sex_series = pd.Series(sex, dtype = "category")
sex_rename = sex_series.cat.rename_categories(['F','M'])


cp = store_data['cp']
cp_series = pd.Series(cp, dtype = "category")
cp_rename = cp_series.cat.rename_categories(["typical","atypical","non-anginal","asymptomatic"])

The output of each looks like this:

>>age_categories
0      (60, 100]
1      (60, 100]
2       (40, 60]

>>sex_rename
0      M
1      M
4      F

>>cp_rename
0           typical
1      asymptomatic
2          atypical

How can I update the original columns with the new transformed values: age_categories, sex_rename, cp_rename? I would like to keep the old names (age, sex, cp) as the head


Solution

  • Try eliminating the extra variables? I haven't run this as there's no data, but this should directly update your dataframe.

    age_bins = [0, 40, 60, 100]
    store_data['age'] = pd.cut(store_data['age'], age_bins)
    

    __

    store_data['sex'] = pd.Series(store_data['sex'], dtype = "category").cat.rename_categories(['F','M'])
    

    __

    store_data['cp'] = pd.Series(store_data['cp'], dtype = "category").cat.rename_categories(["typical","atypical","non-anginal","asymptomatic"])