Skip to content

Instantly share code, notes, and snippets.

@zinyosrim
Created August 9, 2018 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zinyosrim/c7ce8704c1248244358fb99eaeff27e0 to your computer and use it in GitHub Desktop.
Save zinyosrim/c7ce8704c1248244358fb99eaeff27e0 to your computer and use it in GitHub Desktop.
Import grouped data in a CSV into Pandas and substitute NaNs through real data
import csv
reader = csv.reader(open('products.csv'))
products_list = []
first_of_group = ""
for row in reader:
product_name, feature1, feature2 = row
product_dict = {}
if product_name == "":
product_dict["product_name"] = first_of_group
else:
product_dict["product_name"] = product_name
first_of_group = product_name
product_dict["feature1"] = feature1
product_dict["feature2"] = feature2
products_list.append(product_dict)
products_df = pd.DataFrame(products_list)[["product_name", "feature1", "feature2"]]
products_df
a 11 12
13 14
15 16
17 18
19 20
b 21 22
23 24
25 26
c 27 28
29 30
31 32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment