data = {'time': 1603324800, 'url_shares': 50, 'social_score': 165122, 'volume': 98072509, 'market_cap': 75556475}, {'time': 1603411200, 'url_shares': 24, 'social_score': 49081, 'volume': 100253684, 'market_cap': 77036901}, {'time': 1603497600, 'url_shares': 11, 'social_score': 0, 'volume': 72689111, 'market_cap': 75257217}, {'time': 1603584000, 'url_shares': 6, 'social_score': 76225, 'volume': 71654076, 'market_cap': 71411043}, {'time': 1603670400, 'url_shares': 2, 'social_score': null, 'volume': 101958997, 'market_cap': 69759354},
i want to divide the social_score by its previous social_score, and if null/int it should return null, and if the int/null it should return int. but i have no idea how to do so.
CodePudding user response:
It's not entirely clear what "previous" mean in your question, so feel free to swap the roles of i
and i 1
in this answer if I got it wrong.
null = ('__null__',)
data = {'time': 1603324800, 'url_shares': 50, 'social_score': 165122, 'volume': 98072509, 'market_cap': 75556475}, {'time': 1603411200, 'url_shares': 24, 'social_score': 49081, 'volume': 100253684, 'market_cap': 77036901}, {'time': 1603497600, 'url_shares': 11, 'social_score': 0, 'volume': 72689111, 'market_cap': 75257217}, {'time': 1603584000, 'url_shares': 6, 'social_score': 76225, 'volume': 71654076, 'market_cap': 71411043}, {'time': 1603670400, 'url_shares': 2, 'social_score': null, 'volume': 101958997, 'market_cap': 69759354},
results = []
for i in range(len(data)-1):
if data[i 1]['social_score'] not in (null, 0):
results.append(data[i]['social_score'] / data[i 1]['social_score'])
else:
results.append(data[i]['social_score'])
print(results)
# [3.364275381512194, 49081, 0.0, 76225]
Or if you don't like having [ ]
and indices all over the place, using pairwise
:
from itertools import pairwise
from operator import itemgetter
results = [
(x / y if y not in (null, 0) else x)
for x, y in pairwise(map(itemgetter('social_score'), data))
]
print(results)
# [3.364275381512194, 49081, 0.0, 76225]