简体   繁体   中英

How to split a pandas dataframe into columns?

在此处输入图片说明 I have a dataframe that is going to be 100 items long. I am displaying this dataframe on a temporary web template I found online (I don't know html very well). The problem is that the list just makes you scroll all the way down from 1-100, and it looks very bad. I want to have two or three columns side by side (Ex: 33 items in one, then the next 33 in the middle, etc.) so that the dataframe doesn't waste so much space. I don't know if this is an html problem or a problem with the dataframe, so please forgive me.

I am using Flask for the web framework.

If you need me to provide the html code I can.

while counter < 50:
e = str(elem[counter].get_attribute("href"))
e = e.replace("https://www.reddit.com/r/", "")
e = e[:-1]

if e in df['Subreddit'].values:
    df.loc[df['Subreddit'] == e, 'Appearances'] += 1
else:
    df = df.append({'Subreddit': e, 'Appearances': 1}, ignore_index=True)

print(e)
# because there are 2 html tags of the same subreddit name, we have to increment by 2 each time.
counter = counter + 2


df.sort_values(by='Appearances', ascending=False,  inplace=True)
print(df)
df.to_csv(Location, index=False)
browser.close()

The current state is shown in the picture. I would like to have the three columns of data right below that popularsubs area.

Example data:

df = pd.DataFrame(data={'B': ['a', 'b', 's', 'f', 'g', 'r', 'h'], 'A':[1, 2, 3, 4, 5, 6, 7]})

You can split your dataframe to array of dataframes:

size = 3
array = [df.iloc[start: start+size].reset_index() for start in range(0, len(df), size)]

And then concatenate them if you want a single dataframe. I use reset_index to have the same index in all dataframes to concatenate them after. If you don't want concatenate you can do not reset index.

df = pd.concat(array, 1).drop(['index'], 1)

Out:

   B  A  B  A    B    A
0  a  1  f  4    h  7.0
1  b  2  g  5  NaN  NaN
2  s  3  r  6  NaN  NaN

Also if you want you can replace NaN with another value with function df.fillna(value) . Example: df.fillna('') will looks like you have just empty cells in the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM