python - 使用python清理大数据

标签 python pandas

我必须在 python 中清理输入数据文件。由于拼写错误,数据字段可能包含字符串而不是数字。我想识别所有是字符串的字段,并使用 Pandas 用 NaN 填充这些字段。另外,我想记录这些字段的索引。

最粗暴的方法之一是循环遍历每个字段并检查它是否为数字,但是如果数据很大,这会消耗很多时间。

我的 csv 文件包含类似于下表的数据:

Country  Count  Sales
USA         1   65000
UK          3    4000
IND         8       g
SPA         3    9000
NTH         5   80000

.... 假设我在数据中有 60,000 个这样的行。

理想情况下,我想确定 IND 行在 SALES 列下具有无效值。关于如何有效地执行此操作的任何建议?

最佳答案

read_csv 有一个na_values 参数:

na_values : list-like or dict, default None
       Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values

df = pd.read_csv('city.csv', sep='\s+', na_values=['g'])

In [2]: df
Out[2]:
  Country  Count  Sales
0     USA      1  65000
1      UK      3   4000
2     IND      8    NaN
3     SPA      3   9000
4     NTH      5  80000

使用 pandas.isnull ,您只能选择 'Sales' 列或 'Country' 系列中具有 NaN 的那些行:

In [3]: df[pd.isnull(df['Sales'])]
Out[3]: 
  Country  Count  Sales
2     IND      8    NaN

In [4]: df[pd.isnull(df['Sales'])]['Country']
Out[4]: 
2    IND
Name: Country

如果它已经在 DataFrame 中,您可以使用 apply将那些数字字符串转换为整数(使用 str.isdigit ):

df = pd.DataFrame({'Count': {0: 1, 1: 3, 2: 8, 3: 3, 4: 5}, 'Country': {0: 'USA', 1: 'UK', 2: 'IND', 3: 'SPA', 4: 'NTH'}, 'Sales': {0: '65000', 1: '4000', 2: 'g', 3: '9000', 4: '80000'}})

In [12]: df
Out[12]: 
  Country  Count  Sales
0     USA      1  65000
1      UK      3   4000
2     IND      8      g
3     SPA      3   9000
4     NTH      5  80000

In [13]: df['Sales'] = df['Sales'].apply(lambda x: int(x) 
                                                  if str.isdigit(x)
                                                  else np.nan)

In [14]: df
Out[14]: 
  Country  Count  Sales
0     USA      1  65000
1      UK      3   4000
2     IND      8    NaN
3     SPA      3   9000
4     NTH      5  80000

关于python - 使用python清理大数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13867294/

相关文章:

python - 如何在 python 中使用 ctypes 获取 Windows 窗口名称

Python将 map 绘制到球体上

python - 每个键具有多个值的字典列表作为数据框

python - 以行为条件选择 DataFrame 中的列

Python 可执行文件到 Linux 列表文件的大小

python - 从 pandas 系列中删除零的最快方法

python - 我需要如何配置 Keras 模型来预测图像?

python - 迭代数据帧列表并删除特定行

python - 如何从 seaborn/matplotlib 图中删除或隐藏 x 轴标签

python - 以 AM/PM 格式绘制 Pandas Datetime 时间序列