我遇到了一个我认为是非常基本的问题,但我找不到解决方案。简而言之,我在 csv 中有一列是数字列表。此 csv 由 pandas 使用 to_csv 生成。当尝试使用 read_csv 读回它时,它会自动将此数字列表转换为 string。
然后尝试使用它时,我显然会出错。当我尝试使用 to_numeric 函数时,我也遇到了错误,因为它是一个列表,而不是一个数字。
有什么办法可以解决吗?在下面发布表单代码,但可能不是很有帮助:
def write_func(dataset):
features = featurize_list(dataset[column]) # Returns numpy array
new_dataset = dataset.copy() # Don't want to modify the underlying dataframe
new_dataset['Text'] = features
new_dataset.rename(columns={'Text': 'Features'}, inplace=True)
write(new_dataset, dataset_name)
def write(new_dataset, dataset_name):
dump_location = feature_set_location(dataset_name, self)
featurized_dataset.to_csv(dump_location)
def read_func(read_location):
df = pd.read_csv(read_location)
df['Features'] = df['Features'].apply(pd.to_numeric)
Features 列是有问题的。当我尝试运行当前在 read_func 中的 apply 时,出现此错误:
ValueError: Unable to parse string "[0.019636873200000002, 0.10695576670000001,...]" at position 0
我不是第一个遇到这个问题的人,有什么办法可以在读/写时处理这个问题吗?
请您参考如下方法:
您想使用 literal_eval 作为传递给 pd.read_csv 的转换器。以下是其工作原理的示例。
from ast import literal_eval
form io import StringIO
import pandas as pd
txt = """col1|col2
a|[1,2,3]
b|[4,5,6]"""
df = pd.read_csv(StringIO(txt), sep='|', converters=dict(col2=literal_eval))
print(df)
col1 col2
0 a [1, 2, 3]
1 b [4, 5, 6]
