您可以在调用以下命令后使用向量化的字符串方法来解析这些列
read_csv:
import pandas as pdimport decimalD = decimal.Decimaldata = pd.read_csv('data', parse_dates=[[0,1]], infer_datetime_format=True)for col in ('active_accounts', 'transaction_count'): data[col] = data[col].str.replace(r',', '').astype(int)data['transaction_amount'] = (data['transaction_amount'] .str.replace(r'[^-+d.]', '').astype(D))print(data.dtypes)# date_begin_date_end object# name object# name_pre int64# active_accounts int64# transaction_amount object# transaction_count int64# dtype: objectprint(data)产量
date_begin_date_end name name_pre active_accounts 1/1/2008 1/31/2008 Name_1 1001123456 1 2/1/2008 2/29/2008 Name_1 1001 43210 2 3/1/2008 3/31/2008 Name_1 1001485079 3 12/1/2008 12/31/2008 Name_1 1001 87543 4 1/1/2008 1/31/2008 Name_2 1002268456 5 2/1/2008 2/29/2008 Name_2 1002 53210 transaction_amount transaction_count 0 7890123.45 67890 1 987654.32 109876 2 1265789433.98 777888 3 432098987 87987 4 890123.45 97890 5 987654.32 109876
PS。
read_csv确实有一个
converters参数
,您可以使用该参数提供解析有问题的列的函数。每个字符串一次调用这些函数。如果您有很多行,则可能需要很多Python函数调用。如上所示,使用矢量化字符串方法处理列应该更快。
import pandas as pdimport reimport decimalD = decimal.Decimaldef make_parser(cls): def parse_commas(text): return cls(re.sub(r'[^-+d.]', '', text)) return parse_commasto_int = make_parser(int)to_decimal = make_parser(D)data = pd.read_csv('data', parse_dates=[[0,1]], infer_datetime_format=True , converters={4: to_int, 5: to_decimal, 6: to_int})print(data)产量
date_begin_date_end name name_pre active_accounts 1/1/2008 1/31/2008 Name_1 1001123456 1 2/1/2008 2/29/2008 Name_1 1001 43210 2 3/1/2008 3/31/2008 Name_1 1001485079 3 12/1/2008 12/31/2008 Name_1 1001 87543 4 1/1/2008 1/31/2008 Name_2 1002268456 5 2/1/2008 2/29/2008 Name_2 1002 53210 transaction_amount transaction_count 0 7890123.45 67890 1 987654.32 109876 2 1265789433.98 777888 3 432098987 87987 4 890123.45 97890 5 987654.32 109876
且该
transaction_amount列中的值为十进制。
In [64]: data.loc[0, 'transaction_amount']Out[64]: Decimal('7890123.45')


