[英]How do I assign a value to a pandas dataframe cell with a missing value with the value of another cell based on a condition?
I have a dataframe that has some missing values.我有一个 dataframe 有一些缺失值。 I want to replace those missing values with a value from another cell in the dataframe based on a condition.
我想根据条件用 dataframe 中另一个单元格的值替换那些缺失值。 So the dataframe looks like this:
所以 dataframe 看起来像这样:
x ![]() |
a ![]() |
---|---|
xyz ![]() |
A ![]() |
lmn![]() |
B![]() |
None![]() |
A ![]() |
xyz ![]() |
A ![]() |
qrs ![]() |
C ![]() |
None![]() |
B![]() |
What I want to do is set the value of the "None" cell to the value in column x when the values in column a match.我想要做的是当列中的值匹配时,将“无”单元格的值设置为 x 列中的值。 So that it looks like this:
所以它看起来像这样:
x ![]() |
a ![]() |
---|---|
xyz ![]() |
A ![]() |
lmn![]() |
B![]() |
xyz ![]() |
A ![]() |
xyz ![]() |
A ![]() |
qrs ![]() |
C ![]() |
lmn![]() |
B![]() |
The index is just sequential numbers from 0 up and may change depending on the dataset so the index for the cells with the missing information will change.该索引只是从 0 开始的序列号,并且可能会根据数据集而变化,因此具有缺失信息的单元格的索引将发生变化。
You can use ffill()
to fill forward missing values:您可以使用
ffill()
来填充前向缺失值:
df['x'] = df.replace('None', np.nan).groupby('a')['x'].ffill()
print(df)
# Output:
x a
0 xyz A
1 lmn B
2 xyz A
3 xyz A
4 qrs C
5 lmn B
for i in range(len(df)):
if df['a'][i] == 'A':
df['x'][i] = 'xyz'
This worked for me, if you want to do all the other letters, just add an elif
.这对我有用,如果你想做所有其他字母,只需添加一个
elif
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.