[英]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?在具有x和y列的 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.