python - (使用 pandas)数据库单元不会在功能之外更新。该怎么办?
问题描述
因此,我尝试使用其上方和下方行中的值的平均值来填充缺失的数据行。我对编码比较陌生,所以对于任何不简洁的代码,我深表歉意。
以下是我正在使用的功能和一些数据。
import pandas
def avg_round(a,b,c):
x = float(round((a + b)/2,c))
return x
def fill_in_single(c,ro): ##ro signifies to how many digits I need to round the new value to, "c" is the column we need to edit
m_list = single_missing(c) ##this list has all the rows that are empty in the column "c"
for i_obj in m_list:
act_row=i_obj-2 ##I need to do this because the rows are stored as their excel row numbers which is different from the pandas df row number
prev_row=act_row-1
next_row=act_row+1
prev_val=c[prev_row]
next_val=c[next_row]
new_val=avg_round(prev_val,next_val,ro)
df.at[act_row,'{}'.format(c)] = new_val
fill_in_single(Column,0)
print(df.at[2,'Column'])
OUTPUT:
nan
Index Column
0 1
1 9
2
3 0
因此,当我运行它并尝试打印所谓的“更新”列的值时,我得到的是“nan”而不是 new_val。我在函数中运行了这个打印命令,它返回 new_val。我真的不确定该怎么办?
我还在函数之外运行了代码,它会正确更新列。那么为什么这个功能不起作用呢?
解决方案
你可以试试这个
像下面一样先向后和向前填充数据,并在替换时取这两列的平均值nan
df['ffill'] = df['y'].ffill()
df['bfill'] = df['y'].bfill()
df['y'].fillna(df[['ffill', 'bfill']].mean(axis=1))
这是我使用的数据集
d = {'x':['a','a','a','b','b','b','c','c','c','d','d','d'],
'y':[1,np.nan,3,1,2,3,1,np.nan,3,1,2,3]}
df = pd.DataFrame(d)
推荐阅读
- python - 将 Pandas to_json 数据添加到现有 JSON
- flutter - Flutter 异常:使用 Navigator 时出现“上下文不是 BuildContext 的子类型”错误
- javascript - 如何导出 Reflect.defineProperty()?
- javascript - discord.js 无法读取未定义的属性“执行”
- java - Android Canvas Paint:getTextBounds() 忽略系统字体
- typescript - 显式任何字段的隐式任何错误
- reactjs - React Redux:在多个依赖道具上更新组件
- gitlab-ci - 带有 Terraform + Python 的 Gitlab CI / CD
- javascript - 我想为兄弟减速器获得一块状态
- python - 使用基于循环的 numpy 数组创建 DataFrame