import pandas as pd
from ast import literal_eval
import re
from io import StringIO
# pretend to be pygame.Rect
class MockRect:
def __init__(self, left, top, width, height):
self.left, self.top, self.width, self.height = left, top, width, height
def __repr__(self):
return f'pygame.Rect({self.left}, {self.top}, {self.width}, {self.height})'
# to change the string representation of our list of Rects to a string representation of a list of tuples
pattern = re.compile(r'pygame.Rect(\(\d+, \d+, \d+, \d+\))')
# to get back our list of Rects
def to_Rects(rects):
s = pattern.sub(r'\g<1>', rects)
arr = literal_eval(s)
return [MockRect(*tup) for tup in arr]
# create our test DataFrame
d = {
'id': [100, 101],
'rects': [[MockRect(0, 0, 100, 50),
MockRect(0, 50, 100, 50)],
[MockRect(20, 0, 100, 50),
MockRect(20, 20, 100, 50)]],
}
df = pd.DataFrame(d)
print(df)
# create our CSV
b = StringIO()
df.to_csv(b, index=False)
print(b.getvalue())
# read back our CSV
b.seek(0)
df = pd.read_csv(b)
# get back our list of Rects
df.rects = df.rects.apply(to_Rects)
print(df)
我同意@juanpa.arrivillaga在评论中所说的话,但如果你坚持,你可以尝试以下方式:
相关问题 更多 >
编程相关推荐