英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论