数据
data = [
{"content": "1", "title": "app sotre", "info": "", "time": 1578877014},
{"content": "2", "title": "app", "info": "", "time": 1579877014},
{"content": "3", "title": "pandas", "info": "", "time": 1582877014},
{"content": "12", "title": "a", "info": "", "time": 1582876014},
{"content": "33", "title": "apple", "info": "", "time": 1581877014},
{"content": "16", "title": "banana", "info": "", "time": 1561877014},
{"content": "aa", "title": "banana", "info": "", "time": 1582876014},
]我的代码
def cumsum(is_test=False):
cdata = pd.to_numeric(s.str.get('content'), errors='coerce').cumsum()
if is_test:
print(list(cdata))
return list(cdata)
for i, v in enumerate(s):
s.iloc[i]['content'] = str(cdata[i])
return list(s)
assert cumsum(is_test=True)==[1.0, 3.0, 6.0, 18.0, 51.0, 67.0, 'nan']res不是真的,怎么解决?最后如何将我的代码pythonic方式?将cumsum计算的结果替换为指定位置的内容。我希望数据是:
[{'content': '1.0', 'title': 'app sotre', 'info': '', 'time': 1578877014},
{'content': '3.0', 'title': 'app', 'info': '', 'time': 1579877014},
{'content': '6.0', 'title': 'pandas', 'info': '', 'time': 1582877014},
{'content': '18.0', 'title': 'a', 'info': '', 'time': 1582876014},
{'content': '51.0', 'title': 'apple', 'info': '', 'time': 1581877014},
{'content': '67.0', 'title': 'banana', 'info': '', 'time': 1561877014},
{'content': 'nan', 'title': 'banana', 'info': '', 'time': 1582876014}]发布于 2020-03-04 19:38:11
我建议使用Series cdata通过压缩的原始列表data进行循环,然后设置新值:
cdata = pd.to_numeric(s.str.get('content'), errors='coerce').cumsum()
print (cdata)
0 1.0
1 3.0
2 6.0
3 18.0
4 51.0
5 67.0
6 NaN
dtype: float64
for old, new in zip(data, cdata):
old['content'] = str(new)
print (data)
[{'content': '1.0', 'title': 'app sotre', 'info': '', 'time': 1578877014},
{'content': '3.0', 'title': 'app', 'info': '', 'time': 1579877014},
{'content': '6.0', 'title': 'pandas', 'info': '', 'time': 1582877014},
{'content': '18.0', 'title': 'a', 'info': '', 'time': 1582876014},
{'content': '51.0', 'title': 'apple', 'info': '', 'time': 1581877014},
{'content': '67.0', 'title': 'banana', 'info': '', 'time': 1561877014},
{'content': 'nan', 'title': 'banana', 'info': '', 'time': 1582876014}]https://stackoverflow.com/questions/60523176
复制相似问题