Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中填充缺失的数据_Python_Numpy_Pandas_Dataframe - Fatal编程技术网

在Python中填充缺失的数据

在Python中填充缺失的数据,python,numpy,pandas,dataframe,Python,Numpy,Pandas,Dataframe,我希望你能帮我解决一个小问题。 我正在使用一个小设备打印出两个属性,并保存到一个文件中。设备在X和Y方向上光栅化以形成网格。我感兴趣的是绘制这两个属性的相对强度,作为X和Y维度的函数。我将数据记录在以逗号分隔的4列中(X、Y、属性1、属性2)。 网格以直线形式检查,因此对于每个Y值,它将从X1移动到X2,间隔几毫米。然后它将移动到下一行并再次移动 我可以用pandas/numpy在python中处理数据,但是当有任何行丢失时(不幸的是,确实发生了这种情况),它就不能很好地工作。 我附上了一个输出

我希望你能帮我解决一个小问题。 我正在使用一个小设备打印出两个属性,并保存到一个文件中。设备在X和Y方向上光栅化以形成网格。我感兴趣的是绘制这两个属性的相对强度,作为X和Y维度的函数。我将数据记录在以逗号分隔的4列中(X、Y、属性1、属性2)。 网格以直线形式检查,因此对于每个Y值,它将从X1移动到X2,间隔几毫米。然后它将移动到下一行并再次移动

我可以用pandas/numpy在python中处理数据,但是当有任何行丢失时(不幸的是,确实发生了这种情况),它就不能很好地工作。 我附上了一个输出示例(并对问题进行了注释):

44,11500,1
45,11,120,2
46,11,320,3
47,11,700,4

新这是你想要的吗

Q1:使用
reindex
填充
X
,其他使用
fillna

问题2:将分隔的
StringIO
传递到
read\u csv
更容易(如果使用Python 3,则会进行更改)

第一个问题
我在函数中包含了print语句来解释这个函数是如何工作的

In [89]:     
    def replace_missing(df , Ids ):
        # check what are the mssing values
        missing = np.setdiff1d(Ids , df[0])

        if len(missing) > 0 :
            missing_df = pd.DataFrame(data = np.zeros( (len(missing) , 4 )))
            #print('---missing df---')
            #print(missing_df)
            missing_df[0] = missing
            #print('---missing df---')
            #print(missing_df)
            missing_df[1].replace(0 , df[1].iloc[0] , inplace = True)
            #print('---missing df---')
            #print(missing_df)
            df = pd.concat([df , missing_df])
            #print('---final df---')
            #print(df)
        return df

    ​
In [91]:
Ids = np.arange(44,48)
final_df = df1.groupby(df1[1] , as_index = False).apply(replace_missing , Ids).reset_index(drop = True)
final_df
Out[91]:
0   1   2      3
44  11  500    1
45  11  120    2
46  11  320    3
47  11  700    4
45  12  100    5
46  12  1500   6
47  12  2500   7
44  12  0      0
第二个问题
44,11,500,1
45,11,120,2
46,11,320,3
47,11,700,4
New         << used as my Y axis separator
45,12,100,5 << missing 44,12...
46,12,1500,6
47,12,2500,7
 df = pd.read_csv('FileName.csv', delimiter = ',', skiprows=0)
 rows = [-1] + np.where(df['X']=='New')[0].tolist() + [len(df.index)]
 dff = {}
 for i, r in enumerate(rows[:-1]):
     dff[i] = df[r+1: rows[i+1]]
 maxY = len(dff)
 data = []
 data2 = []
 for yaxes in range(0, maxY): 
     data2.append(dff[yaxes].ix[:,2])
 <data2 is then used for plotting using matplotlib>
# read file and split the input 
f = open('temp.csv', 'r')
chunks = f.read().split('New')

# read csv as separated dataframes, using first column as index
dfs = [pd.read_csv(StringIO(unicode(chunk)), header=None, index_col=0) for chunk in chunks]

def pad(df):
    # reindex, you should know the range of x
    df = df.reindex(np.arange(44, 48)) 

    # pad y from forward / backward, assuming y should have the single value
    df[1] = df[1].fillna(method='bfill')
    df[1] = df[1].fillna(method='ffill')
    # padding others
    df = df.fillna(0)
    # revert index to values
    return df.reset_index(drop=False)

dfs = [pad(df) for df in dfs]

dfs[0]
#     0   1    2  3
# 0  44  11  500  1
# 1  45  11  120  2
# 2  46  11  320  3
# 3  47  11  700  4

# dfs[1]
#     0   1     2  3
# 0  44  12     0  0
# 1  45  12   100  5
# 2  46  12  1500  6
# 3  47  12  2500  7
In [89]:     
    def replace_missing(df , Ids ):
        # check what are the mssing values
        missing = np.setdiff1d(Ids , df[0])

        if len(missing) > 0 :
            missing_df = pd.DataFrame(data = np.zeros( (len(missing) , 4 )))
            #print('---missing df---')
            #print(missing_df)
            missing_df[0] = missing
            #print('---missing df---')
            #print(missing_df)
            missing_df[1].replace(0 , df[1].iloc[0] , inplace = True)
            #print('---missing df---')
            #print(missing_df)
            df = pd.concat([df , missing_df])
            #print('---final df---')
            #print(df)
        return df

    ​
In [91]:
Ids = np.arange(44,48)
final_df = df1.groupby(df1[1] , as_index = False).apply(replace_missing , Ids).reset_index(drop = True)
final_df
Out[91]:
0   1   2      3
44  11  500    1
45  11  120    2
46  11  320    3
47  11  700    4
45  12  100    5
46  12  1500   6
47  12  2500   7
44  12  0      0
In [92]:
group = final_df.groupby(final_df[1])

In [99]:
separate = [group.get_group(key) for key in group.groups.keys()]

separate[0]
Out[104]:
0   1   2   3
44  11  500 1
45  11  120 2
46  11  320 3
47  11  700 4