如何从数据框列中提取特定项目并将其用作其余项目的标签?

时间:2018-11-05 13:42:06

标签: python pandas dataframe

我有一个只有一列的数据框,我想提取某些项目并将它们变成一个单独的列,以用作其他剩余项目的标签。例如,如果我拥有的是,这很难解释。

pd.DataFrame({'Fruits': ['Apple', 'Gala', 'Fuji', 'Grannysmith', 'Honeycrisp', 'Golden', 'pink', 'Orange', 'blood orange', 'Mandrin', 'Tangerine', 'Clementine', 'Banana', 'baby', 'manzano', 'burro']})

          Fruits
0          Apple
1           Gala
2           Fuji
3    Grannysmith
4     Honeycrisp
5         Golden
6           pink
7         Orange
8   blood orange
9        Mandrin
10     Tangerine
11    Clementine
12        Banana
13          baby
14       manzano
15         burro

但是我试图将其转换为:

    Fruits  Types
0   Apple   Gala
1   Apple   Fuji
2   Apple   Grannysmith
3   Apple   Honeycrisp
4   Apple   Golden
5   Apple   pink
6   Orange  blood orange
7   Orange  Mandrin
8   Orange  Tangerine
9   Orange  Clementine
10  Banana  baby
11  Banana  manzano
12  Banana  burro

如何将第一个数据帧转换为第二个数据帧?我为此感到难过,尤其是当水果可以有很多种类及其各自类型时。

2 个答案:

答案 0 :(得分:1)

首先需要在列表中定义水果,然后使用whereisin创建带有重复水果的新列以缺失值并向前填充,然后使用boolean indexing删除两列中的相同值最后设置新的列名称:

L = ['Apple','Orange','Banana']

df['a'] = df['Fruits'].where(df['Fruits'].isin(L)).ffill()
df = df.loc[df['a'] != df['Fruits'], ['a','Fruits']]
df.columns = ['Fruits','Types']
print (df)

    Fruits         Types
1    Apple          Gala
2    Apple          Fuji
3    Apple   Grannysmith
4    Apple    Honeycrisp
5    Apple        Golden
6    Apple          pink
8   Orange  blood orange
9   Orange       Mandrin
10  Orange     Tangerine
11  Orange    Clementine
13  Banana          baby
14  Banana       manzano
15  Banana         burro

答案 1 :(得分:1)

我会用一些标准逻辑构建字典映射,然后将其用于Pandas操作

npm install

或者有理解力

fruit_classes = ['Apple', 'Orange', 'Banana']

last_class = None
fruit_map = {}

for fruit in df.Fruits:
  if fruit in fruit_classes:
    last_class = fruit
  elif last_class is not None:
    fruit_map[fruit] = last_class

df.assign(Types=df.Fruits, Fruits=df.Fruits.map(fruit_map)).dropna()

    Fruits         Types
1    Apple          Gala
2    Apple          Fuji
3    Apple   Grannysmith
4    Apple    Honeycrisp
5    Apple        Golden
6    Apple          pink
8   Orange  blood orange
9   Orange       Mandrin
10  Orange     Tangerine
11  Orange    Clementine
13  Banana          baby
14  Banana       manzano
15  Banana         burro

fruit_classes = ['Apple','Orange','Banana']

fruit_classes = ['Apple', 'Orange', 'Banana']