python - 转换数据帧(转置)

标签 python pandas dataframe

我有一个如下所示的数据框:

df=pd.DataFrame(columns=["AC_YEAR","Physics"],data=[[2010,8],[2010,9],[2011,7],[2010,3],[2011,4]])

我想把它改成:

df2=pd.DataFrame(columns=[2010,2011],data=[[8,7],[9,4],[3,]])

我尝试过的一些选项(没有运气)是:

df2 = pd.DataFrame(columns=[])
for year in [2010,2011]:
    pd.concat([df2,(df[df["AC_YEAR"]==year].iloc[:,1])], axis=1, join="inner", ignore_index=True)

有什么帮助吗?谢谢!

最佳答案

您需要通过 cumcount 创建新的索引值或 applySeries 构造函数,最后由 unstack reshape :

df2 = df.set_index([df.groupby('AC_YEAR').cumcount(), 'AC_YEAR'])['Physics'].unstack()

替代解决方案:

df2 = df.groupby('AC_YEAR')['Physics'].apply(lambda x: pd.Series(x.values)).unstack(0)

print (df2)
AC_YEAR  2010  2011
0         8.0   7.0
1         9.0   4.0
2         3.0   NaN

关于python - 转换数据帧(转置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229561/

相关文章:

python - 将标题名称添加到 pandas 数据框中的一组列?

python - 为什么我不能将可选参数默认为成员变量?

python - 在服务器: AttributeError: 'PosixPath' object has no attribute 'startswith' 上运行collectstatic

python - Pandas Dataframe - 从独特的产品中选择

python-3.x - 如何在 pandas group by/nlargest 计算中获取其他列名称信息?

json - 在 FastAPI 应用程序中将 JSON 转换为 DataFrame

python - 修改数据帧列中一对值之间的所有值

jquery - Django django-autocomplete-light 搜索不完整

python - 当输出很大时如何管理Python中的子进程?

python - 类型错误 : This COM object can not automate the makepy process - please run makepy manually for this object