As a practice, I have created the following dataset of reading books:
data = [("Il nome della rosa","Umberto Eco", 1980), ("L'amore che ti meriti","Daria Bignardi", 2014), ("Memorie dal sottsuolo", " Fëdor Dostoevskij", 1864), ("Oblomov", "Ivan Alexandrovich Goncharov ", 1859)] index = range(1,5,1) df = pd.DataFrame(data, columns = ["Books'Title", "Authors", "Publishing Year"], index = index) df
Then I added a fourth column as follows
pubhouses = ["Bompiani", "Mondadori", "Rizzoli", "Feltrinelli"] df.insert(3, 'Publication Houses', pubhouses) df
And now I would like to add as follows (I mean as rows 5 and 6) the following item, always by using the list
l_row = [("Le avventure di Pinocchio", "Carlo Collodi", 1883, "Giunti"), ('Libri che mi hanno rovinato la vita ed altri amori malinconici', "Daria Bignardi", 2022, "Mondadori")]
I have tried adding other titles
l_row = [("Le avventure di Pinocchio", "Carlo Collodi", 1883, "Giunti"), ('Libri che mi hanno rovinato la vita ed altri amori malinconici', "Daria Bignardi", 2022, "Mondadori")]
the following code which does not work:
df.loc[5::6] = l_row df
Since I am at the very beginning I would be very willing to explore different solutions to explore how to add as follows the further list’s names (I thought also about a for loop which I do not how to set out)
Thanks
Advertisement
Answer
Check below code. It uses numpy.vstack to add list rows to existing data frame. Using your code from above for continuity, new code starts after the commented line Adding list rows to dataframe
import pandas as pd import numpy as np data = [("Il nome della rosa","Umberto Eco", 1980), ("L'amore che ti meriti","Daria Bignardi", 2014), ("Memorie dal sottsuolo", " Fëdor Dostoevskij", 1864), ("Oblomov", "Ivan Alexandrovich Goncharov ", 1859)] index = range(1,5,1) df = pd.DataFrame(data, columns = ["Books'Title", "Authors", "Publishing Year"], index = index) pubhouses = ["Bompiani", "Mondadori", "Rizzoli", "Feltrinelli"] df.insert(3, 'Publication Houses', pubhouses) ### Adding list rows to dataframe l_row = [("Le avventure di Pinocchio", "Carlo Collodi", 1883, "Giunti"), ('Libri che mi hanno rovinato la vita ed altri amori malinconici', "Daria Bignardi", 2022, "Mondadori")] pd.DataFrame(np.vstack([df.values, np.vstack(l_row)]), columns = df.columns)