'How to build a dataframe out of a for loop?
I got a dataframe like this one at this link: Dataframe. We got many Cities name and 4 columns for each city. What I would like to do is to extract from this Dataframe the name of 1 or more cities with all their columns i.e If I want to extract Milano and Venezia the output should be of 10 columns (5 columns for Milano and 5 columns for Venezia).
città=["Milano Linate", "Venezia Cavanis"]
estract=[]
for c in città:
a=df.columns.get_loc(c)
estract.append([a,df.iloc[:,a:a+5]])
df_estract=pd.DataFrame(estract)
With these few lines of code I can get what I want, but I am struggling in bulding the new dataframe with the columns I need. Can someone help me with this?
Solution 1:[1]
If you have a dataframe df like
A Unnamed: 2 Unnamed: 3 B Unnamed: 5 Unnamed: 6 C Unnamed: 8 Unnamed: 9
0 1 2 3 4 5 6 7 8 9
1 10 11 12 13 14 15 16 17 18
then this
columns = [c for i in map(df.columns.get_loc, ["A", "B"])
for c in df.columns[i: i + 3]]
df_AB = df[columns]
gives you
A Unnamed: 2 Unnamed: 3 B Unnamed: 5 Unnamed: 6
0 1 2 3 4 5 6
1 10 11 12 13 14 15
So in your case you could try:
columns = [c for i in map(df.columns.get_loc, ["Milano Linate", "Venezia Cavanis"])
for c in df.columns[i: i + 5]]
df_estract = df[columns]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Timus |
