![](/img/trans.png)
[英]In Python, how can I transform a dictionary into a df column, where the keys match the df.index values?
[英]python: Dictionary key as row index, values as column headers. How do I refer back and select specific values in a df using a dictionary?
我有一個看起來像這樣的數據框:
a=['a','b','c','d']
b=['the','fox','the','then']
c=['quick','jumps','lazy','barks']
d=['brown','over','dog','loudly']
df=pd.DataFrame(zip(a,b,c,d),columns=['indexcol','col1','col2','col3'])
和一個看起來像這樣的字典:
keys=['a','b','c','d']
vals=[]
vals.append(['col1','col3'])
vals.append(['col1','col2'])
vals.append(['col1','col2','col3'])
vals.append(['col2','col3'])
newdict = {k: v for k, v in zip(keys, vals)}
我要做的是在 df 中創建一個新列,它為每一行構造一個語句。 以第一行為例,句子應該是這樣的:
“col1 是 'the' | col3 是 '懶惰的'”
另一個使用第三行的例子只是為了使手頭的任務一清二楚:“col1 is 'brown' | col2 is 'the' | col3 is 'then'”
本質上,我想引用字典值以使用字典鍵作為與 df 中 indexcol 匹配的行引用來查找 df 中的列。
提前致謝。
我想這就是你要找的
def func(df_row):
return ' | '.join(
f'"{col}" is "{df_row[col]}"'
for col in newdict[df_row['indexcol']]
)
df['new col'] = df.apply(func, axis=1)
索引庫 | col1 | col2 | col3 | 新山 |
---|---|---|---|---|
一個 | 這 | 快的 | 棕色的 | "col1" 是 "the" | “col3”是“棕色” |
b | 狐狸 | 跳躍 | 超過 | “col1”是“狐狸”| “col2”是“跳躍” |
C | 這 | 懶惰的 | 狗 | "col1" 是 "the" | “col2”是“懶惰的” | “col3”是“狗” |
d | 然后 | 樹皮 | 高聲 | “col2”是“樹皮”| “col3”是“大聲” |
我不確定我是否理解正確,但您可以嘗試:
df = df.set_index("indexcol")
for k, v in newdict.items():
row = df.loc[k]
df.loc[k, "new_column"] = " | ".join(f"{i} is '{row[i]}'" for i in v)
print(df.reset_index())
印刷:
indexcol col1 col2 col3 new_column
0 a the quick brown col1 is 'the' | col3 is 'brown'
1 b fox jumps over col1 is 'fox' | col2 is 'jumps'
2 c the lazy dog col1 is 'the' | col2 is 'lazy' | col3 is 'dog'
3 d then barks loudly col2 is 'barks' | col3 is 'loudly'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.