为什么在大Pandas中输入时,所有的都不转换为小数?

2024-09-29 17:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下代码导入CSV文件。它工作得很好,除非它遇到一个三位数后跟一个十进制数。下面是我的代码和结果

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def fft(x, Plot_ShareY=True): 
    dfs = pd.read_csv(x, delimiter=";", skiprows=(1,2), decimal=",", na_values='NaN') #loads the csv files       
    
    #replaces non-numeric symbols to NaN. 
    dfs = dfs.replace({'-∞': np.nan, '∞': np.nan})
    #print(dfs) #before dropping NaNs
    
    #each column taken into a separate variable
    time = dfs['Time'] #- np.min(dfs['Time']) 
    channelA = dfs['Channel A']
    channelB = dfs['Channel B'] 
    channelC = dfs['Channel C'] 
    channelD = dfs['Channel D']   
    channels = [channelA, channelB, channelC, channelD]   
    
    #printing the smallest index number which is NaN
    ind_num_A = np.where(channelA.isna())[0][0]
    ind_num_B = np.where(channelB.isna())[0][0]
    ind_num_C = np.where(channelC.isna())[0][0]
    ind_num_D = np.where(channelD.isna())[0][0]
    
    ind_num = [ind_num_A, ind_num_B, ind_num_C, ind_num_D]
    
    #dropping all rows after the first NaN is found
    rem_ind = np.amin(ind_num)  #finds the array-wise minimum
    #print('smallest index to be deleted is: ' +str(rem_ind))
    dfs = dfs.drop(dfs.index[rem_ind:])
    print(dfs) #after dropping NaNs

Result

结果与我想要的一样,除了通道B和C中的最后五行,其中显示的是逗号,而不是表示小数点的点。我不知道为什么它在其他地方都能用,但在几排就不行了。CSV文件可以在here找到


Tags: theimportasnpchannelnanwherenum
2条回答

我认为您需要在读取时将非数字符号-∞替换为NaN,而不是在读取之后。如果在创建数据帧后执行此操作,则已读入值,并将其解析为数据类型strintead of float。这会弄乱列的数据类型

因此,不要执行na_values='NaN'操作na_values=["-∞", "∞"],代码如下:

dfs = pd.read_csv(x, delimiter=";", skiprows=(1,2), decimal=",", na_values=["-∞", "∞"])

#replaces non-numeric symbols to NaN. 
# dfs = dfs.replace({'-∞': np.nan, '∞': np.nan}) # not needed anymore

这看起来像是一个数据类型问题。有些值是字符串,因此熊猫在将“,”替换为“.”之前不会自动转换为float

一个选项是在读取文件后使用以下命令转换每一列:df['colname'] = df['colname'].str.replace(',', '.').astype(float)

相关问题 更多 >

    热门问题