- 可以使用以下方法将列从字符串转换回列表:
-
df = pd.read_csv('data.csv', sep='\\s+', index_col=[0], converters={'List_Items': literal_eval}) - 这不适用于此 OP
- 但前提是该列没有格式错误的值(例如
'nan'、'*')
- 在这种情况下需要有一个函数,它可以处理
try-except 的错误
-
df.T.apply(pd.Series.explode).reset_index(drop=True) 用于将每个 list 中的值分隔为单独的行。
- 这仅适用于每个
list 的长度相同的情况,如示例所示。
- 如果列表的长度不同,请改用以下行:
df = pd.concat([df.T[col].explode().reset_index(drop=True) for col in df.T.columns], axis=1)
- 使用
pandas.DataFrame.plot 绘制数据框。
导入和加载数据帧
import pandas as pd
from ast import literal_eval # convert string back to list
import numpy as np
# read the file
df = pd.read_csv('data.csv', sep='\\s+', index_col=[0])
# display(df)
List_Items
Customer
J.B. [13,2,3,4,42,12] ← this is a string
F.C. [1,44,51,24,12,53]
D.S. NaN
B.V. *
F.R. [1,0,0,0,0,0]
功能
# create a function with error handling to convert the column back to lists
def test(row):
try:
row = literal_eval(row) # convert the string to a list
except (ValueError, SyntaxError):
row = np.nan # malformed rows are returned as NaN
return row
修复数据和绘图
# apply the function to the row
df.List_Items = df.List_Items.apply(lambda row: test(row))
# drop nan
df = df.dropna()
# display(df)
List_Items
Customer
J.B. [13, 2, 3, 4, 42, 12] ← this is a list
F.C. [1, 44, 51, 24, 12, 53]
F.R. [1, 0, 0, 0, 0, 0]
# transpose the dataframe and explode the list values to separate rows
df = df.T.apply(pd.Series.explode).reset_index(drop=True)
# display(df)
Customer J.B. F.C. F.R.
0 13 1 1
1 2 44 0
2 3 51 0
3 4 24 0
4 42 12 0
5 12 53 0
# plot
ax = df.plot()