简体   繁体   English

我有一个包含两列的数据框,“主要一个”和“主要两个”。 如何创建一个新专栏“专业”?

[英]I have a dataframe with two columns, “major one” and “major two”. How can I make a new column “majors”?

For example, currently my data looks like (mockup): 例如,目前我的数据看起来像(样机):

In: 在:

print(pandas.pivot_table(dataframe,values='id',index=['major_one','major_two'],columns='status',aggfunc='count',fill_value=fill_character),'\n')

Out: 日期:

status               Registered  Withdrawn
major_one major_two                       
ENGL      BIOL                3          0
          FILM               10          0
BIOL      FILM                4          0
          ENGL                7          1

I want it to look like: 我希望它看起来像:

status  Registered  Withdrawn
majors                       
ENGL           27          1
BIOL            3          0
FILM           14          0

You could try melting your original dataframe before pivoting so that you have a single "majors" column and THEN pivot on the majors column as your index. 您可以尝试在旋转之前熔化原始数据帧,以便在主要列上有一个“majors”列和THEN pivot作为索引。

eg 例如

# pd.melt(df, value_vars = ["major_one", "major_two"], var_name = "major")
# READ EDIT INSTEAD

Read the docs accordingly, the snippet above is based off what I imagine your input data looks like, but you haven't posted a sample at all. 相应地阅读文档,上面的代码段基于我想象的输入数据,但你还没有发布样本。

EDIT: 编辑:

pd.melt(df, value_vars = ['major_one', 'major_two'], var_name = 'major_number', value_name = "major", id_vars = ['id', 'status'])

暂无
暂无

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

相关问题 如何将具有日期时间的DataFrame列拆分为两列:一列是日期,另一列是一天的时间? - How can I split a DataFrame column with datetimes into two columns: one with dates and one with times of the day? 如何用第二个 DataFrame 中的值替换一个 DataFrame 中的列中的值,两者在 Python Pandas 中都有主键? - How to replace values in column in one DataFrame by values from second DataFrame both have major key in Python Pandas? 如何创建新列以跟踪数据框中两列之间的任何更改? - How can I create a new column to track any changes between two columns in a dataframe? 我需要根据 dataframe 的两列生成新列,如何才能更快? - I need to generate new column based on two columns of dataframe, how can it be faster? 如何在数据框中为两行设置一个索引? - How can I have one index for two rows in dataframe? 如何将两列合并为一列 dataframe? - How Can I combine two columns is one dataframe? 如何创建一个包含两列组合的新列? - how can I create a new column with two columns combination? 我从原始数据框中获得了另外两个,如何在最后一个中合并我需要的列 - i have from my original dataframe obtained another two , how can i merge in a final one the columns that i need 我有两列,其中包含列表。如何将这两个列表组合成元素的新列元素 - I have two columns with list in in. How do I combine these two list into a new column element for element 如何在 Python 中将两列合并为一列 - How can I concat two columns into one column in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM