简体   繁体   English

如何使用pandas.melt函数取消几列的同时保持其余列完好无损

[英]How do I use the pandas.melt function to unpivot a few columns while keeping the rest intact

I am working with a database with 66 columns and I wish to unpivot only 3 columns using python pandas.melt function. 我正在使用66列的数据库,我希望使用python pandas.melt函数只pandas.melt 3列。

df = pd.melt(df,value_vars=["RFR 1","RFR 2","RFR 3"],var_name="RFR Index",value_name="RFR Mode")

I'm finding all the other columns are dropped unless I set them as id_vars . 除非我将它们设置为id_vars否则我发现所有其他列都被删除了。 How do I keep them all without listing all of them? 如何在不列出所有内容的情况下保留所有内容? (since there are so many of them) (因为有这么多)

IIUC, you can use pandas.Index.difference to get all columns of your dataframe that are not in your specified list. 在IIUC中,您可以使用pandas.Index.difference来获取数据框中不在指定列表中的所有列。

A bit of a nonsensical example, but: 有点荒谬的例子,但是:

df = pd.DataFrame(data=np.random.randn(5,10),
                  columns=['a','b','c','d','e','f','g','h','i','j'])

val_vars = ['e','f','g']
other_vars = df.columns.difference(val_vars)

df.melt(id_vars=other_vars, value_vars=val_vars)

An alternative approach not using pandas-specific functionality would be to use sets: 不使用pandas特定功能的替代方法是使用集合:

other_vars = set(df.columns) - set(val_vars)

Just create list that doesn't include the columns that are in the value_vars 只需创建不包含value_vars列的value_vars

value_vars = ["RFR 1","RFR 2","RFR 3"]
id_vars = [x for x in df.columns if x not in value_vars]
df = pd.melt(df,value_vars=value_vars,var_name="RFR Index",value_name="RFR Mode", id_vars=id_vars)

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

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