将字典值分配给特定列,根据字典键

huangapple go评论127阅读模式
英文:

Assign dictionary values to specific columns based on dictionary keys

问题

row=[]
对于 k, l 在 names.items() 中
    对于 column 在 countries.columns 中
        如果 k 等于 column
            把 l 添加到 row 中
        否则
            pass
    把 row 添加到 countries_df 的新行中
    增加 i 的值

这段代码的作用是将字典的值分配给特定的列,基于字典的键。如果字典中的键与列名匹配,则将相应的值存储在相应的列中。如果字典中不包含列名的键,则将其设为 Null。

最后的结果应该是:

esp eng mex ger
David Adam Jose
英文:

I need to assign dictionary values to specific columns based on dictionary keys

I have an empty dataframe (countries_df) with only column headers:

| esp | eng | mex | ger |

And a have a dictionary where keys are matching column names:

{'esp': 'David',
'eng': 'Adam',
'mex': 'Jose'}

I need pass value from dictionary to dataframe and store inside columns where column name is equal to key. And if dictionary does not contain key from column names then just pass Null

In the end, it should look like this:

esp eng mex ger
David Adam Jose
row=[]
for k,l in names.items():
        for column in countries.columns:
            if k == column:
                row.append(l)
            else: pass
    countries_df.loc[len(countries_df.index)] = row
    i+=1

It works good if dictionary has 4 keys and df has 4 columns. But in other cases i get "cannot set a row with mismatched columns" error

答案1

得分: 1

让我们使用 concat,它可以处理在 names 字典中缺失/多余的键。

pd.concat([countries_df, pd.DataFrame([names])])

     esp   eng   mex  ger
0  David  Adam  Jose  NaN
英文:

Let us use concat which can handle missing/extra keys in the names dictionary

pd.concat([countries_df, pd.DataFrame([names])])

     esp   eng   mex  ger
0  David  Adam  Jose  NaN

答案2

得分: 0

我已经创建了第一行,然后将新行添加到其中:

import pandas as pd
df = pd.DataFrame({'esp': ['Moses'],
                   'eng': ['Gabriel'],
                   'mex': [None],
                   'ger': ['Stephan']})
row = {'esp': 'David', 'eng': 'Adam', 'mex': 'Jose'}
df = pd.concat([df, pd.DataFrame([row], columns=row.keys())], axis=0)
df

结果如下:

     esp      eng   mex      ger
0  Moses  Gabriel  None  Stephan
0  David     Adam  Jose      NaN
英文:

I have created the first row and then added the new row to it:

import pandas as pd
df = pd.DataFrame({'esp': ['Moses'],
                   'eng': ['Gabriel'],
                  'mex': [None],
                  'ger': ['Stephan']})
row = {'esp': 'David', 'eng': 'Adam', 'mex': 'Jose'}
df = pd.concat([df, pd.DataFrame([row], columns=row.keys())], axis = 0)
df


     esp      eng   mex      ger
0  Moses  Gabriel  None  Stephan
0  David     Adam  Jose      NaN

huangapple
  • 本文由 发表于 2023年7月24日 15:02:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定