[英]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.