Pandas在解析CSV文件时存在千位分隔符后缺失零的问题

3

给定以下内容的csv文件

actual; shouldbe
1,200;  1200
1,2;    1200
12;     12

我希望以一种方式读取内容,使得两列具有相等的值。问题在于千位分隔符后面没有尾随零。

df = pd.read_csv(file, sep=';', thousands=',')

导致
    actual  shouldbe
0   1200    1200
1   12  1200
2   12  12

我希望问题表述清晰。我不知道如何使用Pandas或其他Python和非Python工具来清理我的数据。

2个回答

3

我不确定是否能在加载后不进行数据清洗就完成此操作:

>>> s=u"""actual;shouldbe
... 1,200;1200
... 1,001,21;  1001210
... 1,2;   1200
... 12;   12"""
>>> df = pd.read_csv(StringIO(s), sep=";")
>>> df['result'] = df.actual.apply(lambda x: ''.join(k if i==0 else k.ljust(3, '0') for i,k in enumerate(x.split(','))))
>>> df
     actual  shouldbe   result
0     1,200      1200     1200
1  1,001,21   1001210  1001210
2       1,2      1200     1200
3        12        12       12

2

编辑:出乎意料的是,我发现我的天真解决方案是最快的(甚至比@RomanPekar的解决方案更快)。


最快的解决方案:天真的解决方案

df = pd.read_csv(file, dtype='object')  # to load as string

def fix(string):
    l = string.split(',')
    if len(l) > 1 and len(l[-1]) < 3:
        l[-1] = l[-1] + (3-len(l[-1])) * '0'
    return int(''.join(l))

df['actual'].apply(fix)

最慢的解决方案:向量化解决方案:

missing = (3 - df['actual'].str.split(',').str.get(-1).str.len())
pad = missing.mul(pd.Series(len(missing) * ['0']))
pad = np.where(df['actual'].str.contains(','), pad, '')
pd.to_numeric((df['actual'].str.replace(',', '') + pad))

它只是以向量化的形式执行了朴素方法所做的事情。


性能比较

%timeit df['actual'].apply(fix)
100 loops, best of 3: 5.48 ms per loop

%timeit df.actual.apply(lambda x: ''.join(k if i==0 else k.ljust(3, '0') for i,k in enumerate(x.split(',')))).astype(int)
100 loops, best of 3: 8.34 ms per loop

%timeit pd.to_numeric((df['actual'].str.replace(',', '') + np.where(df['actual'].str.contains(','), (3 - df['actual'].str.split(',').str.get(-1).str.len()).mul(pd.Series(len(df) * ['0'])), '')))
100 loops, best of 3: 12.6 ms per loop

1
谢谢!我认为你的朴素解决方案最易读,所以我接受了你的解决方案。顺便说一下,你的速度测试对我的“真实”数据(约9000个条目)也适用。 - Corvince

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接