Create a DataFrame birds from this dictionary data which has the index labels

前端 未结 4 1764
旧巷少年郎
旧巷少年郎 2021-01-24 08:13

Consider the following Python dictionary data and Python list labels:**

data = {\'birds\': [\'Cranes\', \'Cranes\', \'plovers\', \'spoonbills\', \'spoonbills\',          


        
相关标签:
4条回答
  • 2021-01-24 08:43

    Even I encountered the same exact issue few days back and we have a very beautiful library to handle dataframes and is better than pandas.

    Search for turicreate in python, it is very very similar to the pandas but has a lot more to offer than pandas.

    You can define the Sframes in Turienter image description here, somewhat similar to the pandas dataframe. After that you just have to run:

    dataframe_name.show()

    .show() visualizes any data structure in Turi Create.

    You can visit the mentioned notebook for a better understanding: https://colab.research.google.com/drive/1DIFmRjGYx0UOiZtvMi4lOZmaBMnu_VlD

    0 讨论(0)
  • 2021-01-24 08:44

    Assuming your dictionary is already ordered into the correct ordering for the labels

    import pandas as pd
    
    data = {'birds': ['Cranes', 'Cranes', 'plovers', 'spoonbills', 'spoonbills', 'Cranes', 'plovers', 'Cranes', 'spoonbills', 'spoonbills'],
        'age': [3.5, 4, 1.5, np.nan, 6, 3, 5.5, np.nan, 8, 4],
        'visits': [2, 4, 3, 4, 3, 4, 2, 2, 3, 2],
        'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
    
    data['labels'] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    
    df = pd.DataFrame(data, columns=['birds', 'age', 'visits', 'priority', 'labels'])
    df.set_index('labels')
    
    0 讨论(0)
  • 2021-01-24 08:53

    You can reduce some code like:

    DataFrame provides us a flexibilty to provide some values like data,columns,index and the list goes on.

    If we are dealing with Dictionary, then by default dictionaries keys are treated as column and values will be as rows.

    In following Code I have used name attribute through DataFrame object

    df=pd.DataFrame(data,index=Labels) # Custom indexes
    df.index.name='labels'             # After Running df.index.name you will get index as none, by this approach you can set any name to the column
    

    I hope this will be help full for you.

    0 讨论(0)
  • 2021-01-24 08:59

    Try the code below,

    labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    data = {
        'birds': ['Cranes', 'Cranes', 'plovers', 'spoonbills', 'spoonbills', 'Cranes', 'plovers', 'Cranes', 'spoonbills', 'spoonbills'],
        'age': [3.5, 4, 1.5, np.nan, 6, 3, 5.5, np.nan, 8, 4],
        'visits': [2, 4, 3, 4, 3, 4, 2, 2, 3, 2],
        'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no'],
        'labels' : labels
    }
    df = pd.DataFrame.from_dict(data)
    df.set_index('labels')
    
    0 讨论(0)
提交回复
热议问题