简体   繁体   English

如何将 pandas dataframe 从同名的多行转换为单列?

[英]How to transpose pandas dataframe from multiple rows with same name to single column?

I have tried to convert multiple rows with same name into single column but did not get exactly.我试图将具有相同名称的多行转换为单列,但没有得到准确的结果。 I have done code for single and its mentioned in the following.我已经完成了 single 的代码,下面提到了它。

import pandas as pd 
url = 'https://raw.githubusercontent.com/gambler2020/Data_Analysis/master/population/population.csv'
df=pd.read_csv(url)
df

Image of dataframe The above code used to read and see the data frame from github.But the problem is that there are various countries and each country has hundreds of rows and i want to convert those each country having various rows into single column. dataframe的图像 上面的代码用于读取和查看来自 github 的数据框。但问题是有不同的国家,每个国家都有数百行,我想将每个国家有不同行的数据转换为单列。 The following code is for converting single countries with various rows into one column.以下代码用于将具有不同行的单个国家/地区转换为一列。

dff=df["Year"].head(259)
dff
a1=df[df["Entity"]=="Paraguay"]
a1=a1.rename(columns={"Population (historical estimates)": "Paraguay"})
a1=a1["Paraguay"]
a1=a1.reset_index(drop=True)
a1
dff=pd.concat([dff, a1], axis=1)
dff

image of output result This image is the sample of desired dataframe but it will take time to do for each countries because there are hundreds of countries. output 结果的图像 此图像是所需 dataframe 的样本,但每个国家/地区都需要时间,因为有数百个国家/地区。 How do i write code so that i could convert raw dataframe image into desired output image for all the countries.我如何编写代码以便我可以将原始 dataframe图像转换为所有国家所需的 output图像

pandas.DataFrame.pivot 重塑和数据透视表

result = df.pivot(index='Year', columns='Entity', values='Population (historical estimates)').reset_index()
result.columns.name = None
result

###
      Year  Afghanistan        Africa    Albania     Algeria  American Samoa  …
0   -10000      14737.0  2.276110e+05     1199.0     12090.0             NaN  …
1    -9000      20405.0  3.230350e+05     1999.0     20150.0             NaN  … 
2    -8000      28253.0  4.629670e+05     3332.0     33583.0             NaN  … 
3    -7000      39120.0  6.700190e+05     5554.0     55973.0             NaN  … 
4    -6000      54166.0  9.791040e+05     9256.0     93289.0             NaN  … 
..     ...          ...           ...        ...         ...             ...   
254   2017   36296111.0  1.244222e+09  2884169.0  41389174.0         55617.0  …   
255   2018   37171922.0  1.275921e+09  2882735.0  42228415.0         55461.0  … 
256   2019   38041757.0  1.308064e+09  2880913.0  43053054.0         55312.0  …

[259 rows x 245 columns]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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