Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

python - How to set list to multi-level column in dataframe

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set tuples with pd.Series, because different length of lists:

df[('City_1', 'Lon')] = pd.Series(City_1_lon_list)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...