![](/img/trans.png)
[英]Modify a column in first n rows based on other column value in a DataFrame
[英]Modify part of dataframe's column value based on some other column
我正在嘗試根據另一列的值更新/修改數據框的某些部分。
如果列['a']
為空,則用列['b']
值填充列['a']
,如下所示
list_position = [[4, 35]]
df.iloc[list_position[0][0]:list_position[0][1] + 1,:]['a'] = df.iloc[list_position[0][0]:list_position[0][1] + 1,:].apply(lambda row: row['a'] * row['b'] if np.isnan(row['a']) else row['b'], axis=1)
它給出TypeError: an integer is required
錯誤TypeError: an integer is required
。
Traceback (most recent call last):
File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item
TypeError: an integer is required
任何糾正此問題的建議均受到高度贊賞。
更新1。我嘗試了1種重復答案中建議的所有三種方法
df['Cat1'].fillna(df['Cat2'])
和
在這個帖子上建議了2個答案。
1. df['a'][df['a'].isnull()] = df['b']
2. df['a'] = df['a'].fillna(df['b'])
所有人都給出與以下相同的錯誤:
Traceback (most recent call last):
File "pandas\_libs\index.pyx", line 162, in
pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 958, in
pandas._libs.hashtable.Int64HashTable.get_item
TypeError: an integer is required
如果我將列名替換為列號,則可以正常工作
df[7] = df[7].fillna(df[8)
不知道為什么,如果有人對此有解釋。
這應該在您的情況下有效
df['a'][df['a'].isnull()] = df['b']
我可以看到您要用來完成任務的邏輯,但是有一種更簡單的方法可以完成該任務。
df['a'] = df['a'].fillna(df['b'])
這將用相同索引的b列中的值填充a列中的空值。 但是,如果b列具有空值,而a列具有空值,則a列也將具有空值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.