I have Lat and Lon coordinates for 5 cities. The coordinates are stored in lists named 'City_1_lat_list', 'City_1_lon_list', and so on...
My longest list is 2589 elements long, hence the index range value. I thought I would be able to set the values to the df by assigning the list to the column name ex: df['City_1']['Lon'] = City_1_lon_list
. I also tried converting the list to a Pandas series df['City_1']['Lon'] = pd.Series(City_1_lon_list)
import pandas as pd
import numpy as np
arrays = [
["City_1", "City_1", "City_2", "City_2", "City_3", "City_3", "City_4", "City_4", "City_5", "City_5"],
["Lon", "Lat", "Lon", "Lat", "Lon", "Lat", "Lon", "Lat", "Lon", "Lat"]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(index=np.arange(2589), columns=index[:10])
Is there a way to set a list to a multi-level column in a dataframe without looping through the index?
question from:
https://stackoverflow.com/questions/65841112/how-to-set-list-to-multi-level-column-in-dataframe 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…