简体   繁体   English

如何根据数据框中另一列的值将数据输入到新列中?

[英]How can I enter data into a new column based on the value of another column in a data frame?

I have a very large data frame with campaign finance data - the data frame has a column for the candidate's committee name, but not one for the candidates name.我有一个包含竞选财务数据的非常大的数据框 - 数据框有一列用于候选人的委员会名称,但没有一列用于候选人姓名。

How can I add a new column for the candidates name automatically based on the committee name?如何根据委员会名称自动为候选人名称添加新列? I want the code to read the committee name in each row, and then assign the appropriate candidate name.我希望代码读取每一行中的委员会名称,然后分配适当的候选人姓名。

Assuming there is a one to one mapping between committee name and candidate name, which you can describe in a dictionary, you would just need to use the map function.假设委员会名称和候选人名称之间存在一对一的映射(您可以在字典中描述),您只需要使用map函数。

Example Code:示例代码:

>>> import pandas as pd
>>> data  = pd.DataFrame([["A"], ["B"], ["A"], ["C"]], columns=["Committee Name"])
>>> data
  Committee Name
0              A
1              B
2              A
3              C
>>> committee_name_mapping = {"A": "AName", "B": "BName", "C": "CName"}
>>> data["Candidate Name"] = data["Committee Name"].map(committee_name_mapping)
>>> data
  Committee Name Candidate Name
0              A          AName
1              B          BName
2              A          AName
3              C          CName

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据 Python 中另一个数据框的另一列输入列值 - Enter column value based on another column of another data frame in Python 根据数据框中另一列的值创建新列 - Create new column based on a value of another column in a data-frame 如何计算基于另一列的数据框列中值的频率? - How to count frequency of a value in a column of a data frame based on another column? 如何根据列名将一个数据框中的列值复制到另一个数据框中? - How do I copy the value of columns in one data frame to another data frame based on column names? 如何通过从另一列中的句子中提取单词来在 pandas 数据框中创建一个新列? - How can I create a new column in a pandas data frame by extracting words from sentences in another column? 熊猫:根据另一个数据框中的值在数据框中添加新列 - Pandas: Add a new column in a data frame based on a value in another data frame 根据另一列的值向python pandas数据框添加一列 - Adding a column to a python pandas data frame based on the value of another column pandas:如何根据列值在一个数据帧中从另一个数据帧中 append 行? - pandas: How can I append rows in one data frame from another based on column values? 如何根据最近的标识符将一个数据框的一列添加到另一数据框? - How can I add a column of one data frame to another based on the nearest identifier? Pandas:根据另一个数据框列中的值范围计算单独数据框列框中的值(python) - Pandas: Calculating a value in a separate data frame column frame based on range of values in another data frame column (python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM