Pandas dataframe သို့ အဘိဓာန်ဘယ်လိုပြောင်းရလဲ (ဥပမာ 2 ခု)


Python ရှိ အဘိဓာန်တစ်ခုကို ပန်ဒါ DataFrame အဖြစ်သို့ ပြောင်းလဲရန် အောက်ပါနည်းလမ်းများထဲမှ တစ်ခုခုကို သင်သုံးနိုင်သည်။

နည်းလမ်း 1- dict.items() ကိုသုံးပါ

 df = pd. DataFrame (list(some_dict. items ()), columns = [' col1 ', ' col2 '])

နည်းလမ်း 2- from_dict() ကိုသုံးပါ

 df = pd. DataFrame . from_dict (some_dict, orient=' index '). reset_index ()

df. columns = [' col1 ', ' col2 ']

နည်းလမ်းနှစ်ခုစလုံးသည် တူညီသောရလဒ်ကို ဖြစ်ပေါ်စေပါသည်။

အောက်ဖော်ပြပါ ဥပမာများသည် နည်းလမ်းတစ်ခုစီကို လက်တွေ့အသုံးချနည်းကို ပြသထားသည်။

ဥပမာ 1- dict.items() ကို အသုံးပြု၍ Dictionary ကို DataFrame သို့ ပြောင်းပါ

Python တွင် အောက်ပါအဘိဓာန်ရှိသည်ဆိုပါစို့။

 #create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}

ဤအဘိဓာန်ကို Pandas DataFrame သို့ပြောင်းရန် အောက်ပါကုဒ်ကို ကျွန်ုပ်တို့ အသုံးပြုနိုင်ပါသည်။

 import pandas as pd

#convert dictionary to pandas DataFrame
df = pd. DataFrame (list(some_dict. items ()), columns = [' Player ', ' Points '])

#view DataFrame
df

        Player Points
0 Lebron 26
1 Luke 30
2 Steph 22
3 Nicola 29
4 Giannis 31

ရလဒ်သည် ပန်ဒါ DataFrame ဖြစ်ကြောင်း အတည်ပြုရန် type() လုပ်ဆောင်ချက်ကိုလည်း အသုံးပြုနိုင်သည်။

 #display type of df
type(df)

pandas.core.frame.DataFrame

ဥပမာ 2- အဘိဓာန်ကို from_dict() ကို အသုံးပြု၍ ဒေတာဘောင်သို့ ပြောင်းပါ

Python တွင် အောက်ပါအဘိဓာန်ရှိသည်ဆိုပါစို့။

 #create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}

ဤအဘိဓာန်ကို Pandas DataFrame သို့ပြောင်းရန် အောက်ပါကုဒ်ကို ကျွန်ုပ်တို့ အသုံးပြုနိုင်ပါသည်။

 import pandas as pd

#convert dictionary to pandas DataFrame
df = pd. DataFrame . from_dict (some_dict, orient=' index '). reset_index ()

#define column names of DataFrame
df.columns = [' Player ', ' Points ']

#view DataFrame
df

        Player Points
0 Lebron 26
1 Luke 30
2 Steph 22
3 Nicola 29
4 Giannis 31

ရလဒ်သည် ပန်ဒါ DataFrame ဖြစ်ကြောင်း အတည်ပြုရန် type() လုပ်ဆောင်ချက်ကိုလည်း အသုံးပြုနိုင်သည်။

 #display type of df
type(df)

pandas.core.frame.DataFrame

ဤနည်းလမ်းသည် ယခင်နည်းလမ်းအတိုင်း အတိအကျတူညီသောရလဒ်ကို ထုတ်ပေးကြောင်း သတိပြုပါ။

ထပ်လောင်းအရင်းအမြစ်များ

အောက်ဖော်ပြပါ သင်ခန်းစာများသည် ပန်ဒါများတွင် အခြားဘုံအလုပ်များကို မည်သို့လုပ်ဆောင်ရမည်ကို ရှင်းပြသည်-

Pandas DataFrame ကို Dictionary သို့ဘယ်လိုပြောင်းမလဲ။
Pandas PivotTable ကို DataFrame သို့ဘယ်လိုပြောင်းမလဲ။
Pandas GroupBy output ကို DataFrame သို့ဘယ်လိုပြောင်းမလဲ။

မှတ်ချက်တစ်ခုထည့်ပါ။

သင့် email လိပ်စာကို ဖော်ပြမည် မဟုတ်ပါ။ လိုအပ်သော ကွက်လပ်များကို * ဖြင့်မှတ်သားထားသည်