我有一个包含字符串的数据框,从草率的 csv 中读取:
id Total B C ...
0 56 974 20 739 34 482
1 29 479 10 253 16 704
2 86 961 29 837 43 593
3 52 687 22 921 28 299
4 23 794 7 646 15 600
我想要做的:将框架中的每个单元格转换为数字。它应该忽略空格,但在单元格包含一些非常奇怪的东西的地方放置 NaN 。 我可能知道如何使用性能极差的手动循环和替换值来做到这一点,但想知道是否有一个很好且干净的原因来做到这一点。
最佳答案
您可以使用read_csv
使用正则表达式分隔符 \s{2,}
- 2 个或更多空格和参数 thousands
:
import pandas as pd
from pandas.compat import StringIO
temp=u"""id Total B C
0 56 974 20 739 34 482
1 29 479 10 253 16 704
2 86 961 29 837 43 593
3 52 687 22 921 28 299
4 23 794 7 646 15 600 """
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), sep="\s{2,}", engine='python', thousands=' ')
print (df)
id Total B C
0 0 56974 20739 34482
1 1 29479 10253 16704
2 2 86961 29837 43593
3 3 52687 22921 28299
4 4 23794 7646 15600
print (df.dtypes)
id int64
Total int64
B int64
C int64
dtype: object
然后如有必要应用
函数 to_numeric
使用参数 errors='coerce'
- 它将非数字替换为 NaN
:
df = df.apply(pd.to_numeric, errors='coerce')
关于python - Pandas:清理 DataFrame 并将其转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42898952/