【问题标题】:Pandas tuple with value and dictionary into dataframe带有值和字典的熊猫元组进入数据框
【发布时间】:2019-04-24 07:25:25
【问题描述】:

目前,我有以下形式的数据:

即。

[ ('ab', {'a' : [apple1], 'b': [ball1]}), ('cd', {'a' : [apple2], 'b':   [ball2]})]  

List[Tuple[Any, dict{'key':List}]]

目标是创建如下形式的 pandas 数据框:

start   a             b
ab    apple1         ball1
cd    apple2         ball2

我尝试过以下方式:

df = pd.DataFrame(columns=['start', 'a', 'b'])
for start, details in mylist:
    df = df.append({'start' : start}, ignore_index= True)
    df = df.append({'a' : details['a']} , ignore_index= True)
    df = df.append({'b': details['b']}, ignore_index=True)

我正在尝试找出一种优化的方法来做到这一点。

【问题讨论】:

  • 已用尝试过的代码更新

标签: python pandas numpy dictionary dataframe


【解决方案1】:

像这样:

form = [ ('ab', {'a' : ['apple1'], 'b': ['ball1']}), ('cd', {'a' : ['apple2'], 'b':   ['ball2']})]

# separate 'start' from rest of data - inverse zip
start, data = zip(*form)

# create dataframe
df = pd.DataFrame(list(data))

# remove data from lists in each cell
df = df.applymap(lambda l: l[0])

df.insert(loc=0, column='start', value=start)

print(df)
     start     a      b
0    ab   apple1  ball1
1    cd   apple2  ball2

或者,如果你想开始成为数据框的索引:

# separate 'start' from rest of data - inverse zip
index, data = zip(*form)

# create dataframe
df = pd.DataFrame(list(data), index=index)
df.index.name = 'start' 

# remove data from lists in each cell
df = df.applymap(lambda l: l[0])

print(df)
start     a      b
ab   apple1  ball1
cd   apple2  ball2

【讨论】:

    【解决方案2】:

    pd.DataFrame.from_dict

    Pandas 可以很好地配合字典字典列表。你有一些介于两者之间的东西。在这种情况下,转换为字典很简单:

    L = [('ab', {'a' : ['apple1'], 'b': ['ball1']}),
         ('cd', {'a' : ['apple2'], 'b': ['ball2']})]
    
    res = pd.DataFrame.from_dict(dict(L), orient='index')
    res = res.apply(lambda x: x.str[0])
    
    print(res)
    
             a      b
    ab  apple1  ball1
    cd  apple2  ball2
    

    【讨论】:

    • res.apply(lambda x: x.str[0])?的目的是什么
    • 您的内部字典中有列表,这是从每个列表中提取第一个(也是唯一一个)元素的一种方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2017-04-20
    • 2021-02-15
    • 2021-11-19
    相关资源
    最近更新 更多