Convert dataframe to specific list (index)

  Kiến thức lập trình

I would like to know if it is possible to convert this kind of dataframe:

df = pd.DataFrame([['Value1', 1], ['Value3', 3], ['Value4', 4]], columns=['Value', 'Type'])

Into a list which consider column “Type” as index of list and “Value” as value of list like this(no index in the dataframe involves no value):

List= ["","Value1", "", "Value3","Value4"]

I can create this list by parsing the dataframe but I would like to know if there is a better way to achieve this.
Currently there is the parsing:

last=df["Type"].max()
liste=[]
index_list=0
index_df=0
while index_list<=last:
    if df["Type"].iloc[index_df]==index_list:
        liste.insert(index_list, df["Value"].iloc[index_df])
        index_df=index_df+1
    else:
        liste.insert(index_list, "")
    index_list=index_list+1

Thank you

10

not sure if you have typos in your desired/expected result or that you’ve actually added a ‘Value1’ entry manually to List ? (only you know)!

df = pd.DataFrame([['Value2', 2], ['Value3', 3], ['Value4', 4]], columns=['Value', 'Type'])
print(df)

alist = ["", "", "Value1"] + df['Value'].tolist()
print(alist)

produces

    Value  Type
0  Value2     2
1  Value3     3
2  Value4     4

['', '', 'Value1', 'Value2', 'Value3', 'Value4']

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT