我正在使用以下代码导入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
结果与我想要的一样,除了通道B和C中的最后五行,其中显示的是逗号,而不是表示小数点的点。我不知道为什么它在其他地方都能用,但在几排就不行了。CSV文件可以在here找到
我认为您需要在读取时将非数字符号
-∞
和∞
替换为NaN
,而不是在读取之后。如果在创建数据帧后执行此操作,则已读入值,并将其解析为数据类型str
intead offloat
。这会弄乱列的数据类型因此,不要执行
na_values='NaN'
操作na_values=["-∞", "∞"]
,代码如下:这看起来像是一个数据类型问题。有些值是字符串,因此熊猫在将“,”替换为“.”之前不会自动转换为float
一个选项是在读取文件后使用以下命令转换每一列:
df['colname'] = df['colname'].str.replace(',', '.').astype(float)
相关问题 更多 >
编程相关推荐