简体   繁体   English

如何根据条件为具有缺失值的 pandas dataframe 单元格分配另一个单元格的值?

[英]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 X a A
xyz xyz A A
lmn半月 B
None没有任何 A A
xyz xyz A A
qrs qrs C 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 X a A
xyz xyz A A
lmn半月 B
xyz xyz A A
xyz xyz A A
qrs qrs C 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.

相关问题 为熊猫数据框中的单元格赋值 - Assign value to cell in pandas dataframe 如何根据条件在 Pandas dataframe 的单个单元格中列出 append 值 - How to append value to list in single cell in Pandas dataframe based on condition 如何根据两个条件将数据框的单元格值相乘? - How can i multiply a cell value of a dataframe based on two condition? 如何使用 Pandas 在 Python 中基于同一行中的另一个单元格设置单元格值 - How do I set a cell value based on another cell in same row in Python Using Pandas 根据将另一个单元格与另一个数据框的单元格进行比较来更改一个数据框中单元格的值 - 熊猫 - Changing value of cell in one dataframe based on comparision another cell to another dataframe's cell - pandas 为单元格赋值 dataframe - Assign a value to a cell 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? 如何修改包含列表的 pandas dataframe 单元格的值? - How do I modify the value of a pandas dataframe cell that contains a list in it? 单元格中的值是列表时的熊猫数据框条件 - Pandas dataframe condition when value in cell is a list 根据条件在 Pandas 数据框中迭代和赋值 - Iterate and assign value in Pandas dataframe based on condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM