I want to add a new category into my existing column based on some conditions like: child category is female age- male age
import pandas as pd
d = {'gender': ['male', 'female'], 'age': [3, 4]}
df = pd.DataFrame(data=d)
print(df)
gender age
male 3
female 4
output required:
gender age
male 3
female 4
child 1
CodePudding user response:
you can add a row using DataFrame.append()
like this
import pandas as pd
d = {'gender': ['male', 'female'], 'age': [3, 4]}
df = pd.DataFrame(data=d)
df
gender | age |
---|---|
0 | male |
1 | female |
d2 = {'gender': ['child'], 'age': [1]}
d2 = pd.DataFrame(data=d2)
df = df.append(d2)
df
gender | age |
---|---|
0 | male |
1 | female |
2 | child |
CodePudding user response:
I don't understand the logic behind this but you can use append
:
age = df.loc[df['gender'] == 'female', 'age'].squeeze() \
- df.loc[df['gender'] == 'male', 'age'].squeeze()
df = df.append({'gender': 'child', 'age': age}, ignore_index=True)
Output:
>>> df
gender age
0 male 3
1 female 4
2 child 1