Python:字典键作为行索引,值为列标题。如何使用词典中回顾DF中的特定值?
我有一个看起来像这样的数据框:
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是''| col3是'懒''”
另一个示例使用第三行只是为了使手动晶体的任务清晰: “ col1是'brown'| col2是'| col3是'then''“
从本质上讲,我想使用字典键在df中查找DF中的列,作为与DF中的indexCol匹配的行。
提前致谢。
I have a dataframe that looks like this:
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'])
and a dictionary that looks like this:
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)}
What I'm trying to do is to create a new column in df which constructs a statement for each row. Taking the first row as an example, the sentence should look like so:
"col1 is 'the' | col3 is 'lazy' "
another example using the 3rd row just to make the task at hand crystal clear:
"col1 is 'brown' | col2 is 'the' | col3 is 'then' "
essentially, I want to refer to the dictionary values to look up the column in df using the dictionary keys as the row reference matching to indexcol in df.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是您正在寻找
I guess this is what you're looking for
我不确定我是否正确理解您,但您可以尝试:
打印:
I'm not sure if I understand you correctly but you can try:
Prints: