Reputation: 1
I need to do repetitive coding for many years, for instance,
G1990 = pd.read_csv("map_1990.csv")
G1991 = pd.read_csv("map_1991.csv")
". . ."
G2015 = pd.read_csv("map_2015.csv")
Other examples are,
path2001=dict(nx.all_pairs_shortest_path_length(G2001))
path2002=dict(nx.all_pairs_shortest_path_length(G2002))
path2003=dict(nx.all_pairs_shortest_path_length(G2003))
". . . "
path2015=dict(nx.all_pairs_shortest_path_length(G2015))
and
df2001.to_csv("path2001.csv")
df2002.to_csv("path2002.csv")
df2003.to_csv("path2003.csv")
". . . "
df2015.to_csv("path2015.csv")
it would be nice if I can use a loop to simplify my code, such that
for i in range(1990:2015),
G[i] = pd.read_csv("map_[i].csv")
or
for i in range(2001:2015),
path[i]=dict(nx.all_pairs_shortest_path_length(G[i]))
and
for i in range(1990:2015),
df[i].to_csv("path[i].csv")
Help me please :)
Upvotes: 0
Views: 87
Reputation: 12015
Yes. Of course you can do it as follow:
G = {}
for i in range(1990, 2016):
G[i] = pd.read_csv(f"map_{i}.csv")
or, in short:
G = {i: pd.read_csv(f"map_{i}.csv") for i in range(1990, 2016)}
Upvotes: -1
Reputation: 1
g = {}
for i in range(1900,2015):
g[i] = pd.read_csv('map_'+ str(i) + '.csv')
Upvotes: 0
Reputation: 365925
it would be nice if I can use a loop to simplify my code, such that
for i in range(1990:2015),
G[i] = pd.read_csv("map_[i].csv")
You just need to fix the syntax a bit.
:
is for slices, not ranges; you need range(1990, 2015)
.range(1990, 2015)
would not include 2015.for
statements, and all compound statements in Python, need a :
at the end.G
before you can add things to it.{}
rather than []
.f
.1So:
eggs = {}
for i in range(1990, 2016):
eggs[i] = pd.read_csv(f"map_{i}.csv")
1. If you're using Python 3.5 or earlier, including 2.7, you can't use f-strings; instead, you have to write "map_{}.csv".format(i)
.
Upvotes: 4