python - 将列移到左侧 Pandas Dataframe

标签 python pandas dataframe

我有一个包含名称、颜色、重量、大小、种子的水果数据集

         Fruit dataset

         Name     Colour    Weight  Size   Seeds   Unnamed

         Apple    Apple     Red     10.0   Big     Yes  

         Apple    Apple     Red     5.0    Small   Yes  

         Pear     Pear      Green   11.0   Big     Yes  

         Banana   Banana    Yellow  4.0    Small   Yes  

         Orange   Orange    Orange  5.0    Small   Yes  

问题在于,color 列是 name 的重复列,值向右移动 1 列,创建了一个无用的列(未命名),其中包含属于 Seeds 列的值。有没有一种简单的方法可以删除 Color 中的重复值,并将其余列值从 weight 向左移回 1 列。我希望我不会混淆这里的任何人。

想要的结果

         Fruit dataset

         Name     Colour  Weight Size    Seeds   Unnamed(will be dropped)

         Apple    Red     10.0   Big     Yes  

         Apple    Red     5.0    Small   Yes  

         Pear     Green   11.0   Big     Yes  

         Banana   Yellow  4.0    Small   Yes  

         Orange   Orange  5.0    Small   Yes  

最佳答案

你可以这样做:

In [23]: df
Out[23]:
     Name  Colour  Weight  Size  Seeds Unnamed
0   Apple   Apple     Red  10.0    Big     Yes
1   Apple   Apple     Red   5.0  Small     Yes
2    Pear    Pear   Green  11.0    Big     Yes
3  Banana  Banana  Yellow   4.0  Small     Yes
4  Orange  Orange  Orange   5.0  Small     Yes

In [24]: cols = df.columns[:-1]

In [25]: cols
Out[25]: Index(['Name', 'Colour', 'Weight', 'Size', 'Seeds'], dtype='object')

In [26]: df = df.drop('Colour', 1)

In [27]: df.columns = cols

In [28]: df
Out[28]:
     Name  Colour  Weight   Size Seeds
0   Apple     Red    10.0    Big   Yes
1   Apple     Red     5.0  Small   Yes
2    Pear   Green    11.0    Big   Yes
3  Banana  Yellow     4.0  Small   Yes
4  Orange  Orange     5.0  Small   Yes

关于python - 将列移到左侧 Pandas Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544975/

相关文章:

python - 列表中的换行符不打印在单独的行上

python - 按列对 csv 进行排序时出错

python - 基于日期范围的虚拟变量操作

python - pandas IndexError/TypeError 与 NaN 值不一致

excel - Python - XlsxWriter : Referring to columns by column name, 不是列字母(硬编码与动态变量)

r - 在 R 中从列表转换为 data.frame 时,utf-8 字符会丢失

python - 无论如何,是否可以将事件处理程序绑定(bind)到正在移动的 Tkinter 窗口?

python - django:模板中字符串的神秘填充

python - 从 Google Drive 创建完整的文件夹结构,包括路径

python - 使用一致的映射跨数据框列分解值