![](/img/trans.png)
[英]Pandas - read csv stored as string in memory to data frame
[英]How to read a np matrix from a pandas data frame stored in .csv?
我試圖從存儲在 a.csv 中的另一個 pandas 數據幀中讀取 np.matrix 和 pandas 數據幀
我試過使用文字 eval 但它不起作用。
Etapa=pd.read_csv(f"data/etapas.csv",encoding="latin_1")
from ast import literal_eval
Etapa.loc[:,"Etapa"]=Etapa.Etapa.map(literal_eval)
Etapa.loc[:,"MatrizTiempos"]=Etapa.MatrizTiempos.apply(literal_eval)
Etapa.loc[:,"DataFrameEscuelas"]=Etapa.DataFrameEscuelas.map(literal_eval)
出現的錯誤是這樣的:
文件“”,第 1 行 [[0. 0. 0. 0.] ^ 語法錯誤:語法無效
現在,您有一個語法不正確的list
的字符串表示形式:
from ast import literal_eval
x = '[[0. 0. 0.], [1. 1. 1.]]'
literal_eval(x)
File "<unknown>", line 1
[0. 0. 0.]
^
SyntaxError: invalid syntax
我假設小數點在那里,因為可能有浮點數:
from ast import literal_eval
x = '[[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]'
literal_eval(''.join( # join back string fragments
', '.join(
a.split(' ') # split on whitespace and join on commas
) for a in x.split(',')
))
[[0, 0, 0], [1, 1, 1], [1.3, 4.4, 5.5]]
將此轉換為您的 dataframe 實現:
import pandas as pd
from ast import literal_eval
def to_list(x):
return literal_eval(''.join(', '.join(a.split(' ')) for a in x.split(',')))
mystr = '[[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]'
df = pd.DataFrame([{0: mystr} for i in range(5)])
df[0]
0 [[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]
1 [[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]
2 [[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]
3 [[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]
4 [[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]
Name: 0, dtype: object
# these are all string types
df[0][0]
'[[0. 0. 0.], [1. 1. 1.], [1.3 4.4 5.5]]'
df[1] = df[0].map(to_list)
# this is now a list type
df[1][0]
[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [1.3, 4.4, 5.5]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.