[英]Join two pandas dataframe columns row-wise
Assuming I have a pandas dataframe df
, whereby df is:假设我有一个 pandas dataframe
df
,其中 df 是:
vaccine age height
0 pfizer 48.0 181.0
1 moderna 81.0 175.0
2 moderna 27.0 190.4
3 moderna 64.0 178.5
I am trying to join the two columns (age, height) into a single column row-wise, whereby age and height are grouped by their respective vaccine.我正在尝试将两列(年龄,身高)按行连接成一列,其中年龄和身高按各自的疫苗分组。
Basically, I am trying to get:基本上,我试图得到:
vaccine new_col
0 pfizer 48.0
1 pfizer 181.0
2 moderna 81.0
3 moderna 175.0
4 moderna 27.0
5 moderna 190.4
6 moderna 64.0
7 moderna 178.5
I have unsuccessfully tried using pd.concat, df.merge, etc. I am not familiar with any pandas function that does this.我没有成功尝试使用 pd.concat、df.merge 等。我不熟悉任何这样做的 pandas function。 I also tried using the apply function but I wasn't successful.
我也尝试使用 apply function 但我没有成功。
First set the index as vaccine
then stack
the dataframe, and drop index level at 1, finally reset the index.首先将索引设置为
vaccine
然后stack
dataframe,并将索引级别降至1,最后重置索引。
df.set_index('vaccine').stack().droplevel(1).to_frame('new_col').reset_index()
vaccine new_col
0 pfizer 48.0
1 pfizer 181.0
2 moderna 81.0
3 moderna 175.0
4 moderna 27.0
5 moderna 190.4
6 moderna 64.0
7 moderna 178.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.