【问题标题】:Why are my values not replaced in CSV files using np.nan?为什么我的值没有在使用 np.nan 的 CSV 文件中替换?
【发布时间】:2021-09-11 23:12:16
【问题描述】:

我是 python 新手,在将 CSV 文件中低于某个阈值的值更改为 NaN 时遇到问题。

我在一个数据集上运行良好的脚本,但在另一个数据集上运行良好。这些数据集的主要区别在于 CSV 文件的尺寸:1800 行 x 13 列与 1800 行 x 28 列。这些列包含从视频分析得出的不同身体部位的 x、y 位置和似然值。

这是我用来检查 CSV 文件中的值是否更改为 NaN 的代码。

import pandas as pd
import numpy as np
  

absolute_path = 'mypath/example.csv'
p_cutoff = 0.9

df = pd.read_csv(absolute_path, header=[1,2], index_col=0)

print(df.head)

print('before: ')
print(df.isna().sum())

for i, row in df.iterrows():
    if df.loc[i]['arm_L']['likelihood'] < p_cutoff:
        df.loc[i]['arm_L']['x'] = np.nan
        df.loc[i]['arm_L']['y'] = np.nan

print('')
print('after: ')
print(df.isna().sum())

print(df.head)

当数据框有 13 列时,将 x 和 y 坐标更改为 nan 有效,但是当我在只有一个额外列(即更多身体部位)的数据框上尝试它时,x-y 值不是换了。

有人知道怎么解决吗?

Example narrow data frame:

Example wide data frame:

Expected outcome

【问题讨论】:

    标签: python pandas numpy csv


    【解决方案1】:

    这是因为方法 loc 使用多个列的方式,尽管您可以通过较小的更改使其成为您的方式,如果您使用 import pandas as pd,它的计算速度会更快 将 numpy 导入为 np

    absolute_path = 'mypath/example.csv'
    p_cutoff = 0.9
    
    df = pd.read_csv(absolute_path, header=[1,2], index_col=0)
    
    print(df.head)
    
    print('before: ')
    print(df.isna().sum())
    
    for col in ['x', 'y']
        df['arm_L'][col] = np.where(df['arm_L']['likelihood'] < p_cutoff, 
                                    np.nan, df['arm_L'][col])
    
    print('')
    print('after: ')
    print(df.isna().sum())
    
    print(df.head)
    

    【讨论】:

    • 谢谢,它似乎更快,但我仍然没有在宽数据框中得到 nan。
    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多