简体   繁体   English

在 Python 中,如何根据另一列更改 dataframe 的一列?

[英]In Python, how do I change one column of a dataframe based on another?

In a dataframe with columns x and y , how would I write code so that if a row has an x string but a 'Not assigned' y string (the y column contains the string "Not assigned"), then the y string will be the same as the x string?在具有xy列的 dataframe 中,我将如何编写代码以便如果一行有一个x字符串但一个“未分配” y字符串( y列包含字符串“未分配”),那么y字符串将是和x字符串一样吗?
(Overwriting the "Not assigned" string in column y with the contents of column x ) (用列x的内容覆盖列y中的“未分配”字符串)

You can use df.iterrows() checking the values of the columns conditionally as you iterate.您可以在迭代时使用df.iterrows()有条件地检查列的值。

import pandas as pd

df = pd.DataFrame(data={'x': [1,2,3], 'y': [6, "Not Assigned", 8]})

for index, value in df.iterrows():
  if value['y'] == 'Not Assigned':
    df['y'][index] = df['x'][index]

Output: Output:


    x   y
0   1   6
1   2   2
2   3   8
df.loc[df['y']=='Not assigned', 'y'] = df.loc[df['y']=='Not assigned', 'x']

would do it会做的

暂无
暂无

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

相关问题 如何将基于列的 dataframe 中的值添加到基于行的另一个 dataframe 中? - How do I add the value from one dataframe based on a column to another dataframe based on a row? 如何使用 Python 查看数据框中一列的值并根据这些结果在另一列中附加一个新值? - How do I use Python to look at the values of one column in a dataframe and append a new value in another column based on those results? 如何使用基于另一个DataFrame的列将一个DataFrame列转移到真值表? - How do I pivot one DataFrame column to a truth table with columns based on another DataFrame? 我如何根据列单元格值和 append 查找一个 dataframe 上的一行到另一个 dataframe 上的一行? - How do i lookup a row on one dataframe based on the column cell value and append that to a row on another dataframe? Python:在DataFrame中,如何查找某一列中的字符串出现在另一列中的年份? - Python: In a DataFrame, how do I find the year that strings from one column appear in another column? 如何使用python将数据框中的一列值更改为另一列值 - How to change values from one column to another in a dataframe using python 如何为基于另一个DataFrame的字符串创建标签列? - How do I create a labeling column for strings based on another DataFrame? 如何通过将python中的目标列的多列与另一数据帧中的一列进行匹配来更新数据框中的目标列的某些值? - How do I update some values of my target column in a dataframe by matching its multiple columns with one column in another dataframe in python? 如何将数据从一列移动到另一列 Python DataFrame - How do I move data from one column to another in Python DataFrame 如何通过在 Python DataFrame 中保持某些列值不变来将数据从一行合并到另一行 - How do I merge data from one row to another by keeping some column values unchanged in Python DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM