I have a pandas dataframe that contains the iris dataset. I want to subset this dataframe to only include sepal_length and species, and then reshape it so that the columns are the unique values for species and the values are the values for that species.
# load data into a dataframe
df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
head(df)
+----+---------------+--------------+---------------+--------------+---------+
| | sepal_length | sepal_width | petal_length | petal_width | species |
+----+---------------+--------------+---------------+--------------+---------+
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
+----+---------------+--------------+---------------+--------------+---------+
I can do this is I take the data out of Pandas as use a dictionary to reshape the data, but I can't figure out how to do it within pandas.
data = df.to_dict('records')
e = {}
for line in data:
e[line['species']] = []
for line in data:
e[line['species']].append(line['sepal_length'])
new = pd.DataFrame(e)
This is what I want to end up with:
+----+---------+-------------+-----------+
| | setosa | versicolor | virginica |
+----+---------+-------------+-----------+
| 0 | 5.1 | 7.0 | 6.3 |
| 1 | 4.9 | 6.4 | 5.8 |
| 2 | 4.7 | 6.9 | 7.1 |
| 3 | 4.6 | 5.5 | 6.3 |
| 4 | 5.0 | 6.5 | 6.5 |
+----+---------+-------------+-----------+
I've tried using pd.crosstab(df['sepal_length'], df['species']) but that doesn't get me what I want. I've also tried using df.pivot_table('sepal_length', columns='species') and that also isn't it.
What am I missing here?