'How to make my code to display only one item from pandas dataset?
Code sample :
def parse_first_name_female(name):
first = name.str.extract(r"Mrs\.\s+[^(]*\((\w+)", expand=False)
first.loc[first.isna()] = name.str.extract(r"\.\s+(\w+)", expand=False)
return first
female_names = parse_first_name_female(dataset.loc[dataset['Sex']=='female', 'Name'])
This code returns:
print(female_names)
1 Florence
2 Laina
3 Lily
8 Elisabeth
9 Adele
...
880 Imanita
882 Gerda
885 Margaret
887 Margaret
888 Catherine
I need this code just first name to return('Florence')
Solution 1:[1]
Are you looking for .iloc?
def parse_first_name_female(name):
first = name.str.extract(r"Mrs\.\s+[^(]*\((\w+)", expand=False)
first.loc[first.isna()] = name.str.extract(r"\.\s+(\w+)", expand=False)
return first
female_names = parse_first_name_female(dataset.loc[dataset['Sex']=='female', 'Name'])
print(female_names.iloc[0])
# Output
Florence
Setup:
df = pd.DataFrame({'Name': ['Braund, Mr. Owen Harris', 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)', 'Heikkinen, Miss. Laina', 'Futrelle, Mrs. Jacques Heath (Lily May Peel)', 'Allen, Mr. William Henry', 'Moran, Mr. James', 'McCarthy, Mr. Timothy J', 'Palsson, Master. Gosta Leonard', 'Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)', 'Nasser, Mrs. Nicholas (Adele Achem)'],
'Sex': ['male', 'female', 'female', 'female', 'male', 'male', 'male', 'male', 'female', 'female'],
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Corralien |
