2017-07-15 19 views
2

生のテキストファイルからデータフレームを作成するためにPandasを使用しようとしています。このファイルには、カテゴリ名の後に各カテゴリに関連する項目を含む3つのカテゴリが含まれています。カテゴリに基づいてシリーズを作成することはできますが、各アイテムタイプをそれぞれのカテゴリに関連付ける方法と、そこからデータフレームを作成する方法はわかりません。以下は私の初期コードとデータフレームの望ましい出力です。これを行うには正しい方法で私を指示するのを助けてくれますか?Python Pandasテキストファイルを使用してデータフレームを作成する

category = ['Fruits', 'Vegetables', 'Meats'] 

items='''Fruits 
apple 
orange 
pear 
Vegetables 
broccoli 
squash 
carrot 
Meats 
chicken 
beef 
lamb''' 

Category = pd.Series() 

i = 0 
for item in items.splitlines(): 
    if item in category: 
     Category = Category.set_value(i, item) 
     i += 1 
df = pd.DataFrame(Category) 
print(df) 

希望DATAFRAME出力:

Category Item 
Fruits  apple 
      orange 
      pear 
Vegetables broccoli 
      squash 
      carrot 
Meats  chicken 
      beef 
      lamb 

答えて

0

リストの代わりに、一連の辞書に反復的に追加することを検討してください。次に、dictをdataframeにキャストします。

from io import StringIO 
import pandas as pd 

txtobj = StringIO('''Fruits 
apple 
orange 
pear 
Vegetables 
broccoli 
squash 
carrot 
Meats 
chicken 
beef 
lamb''') 

items = {'Category':[], 'Item':[]} 

for line in txtobj: 
    curr_line = line.replace('\n','') 
    if curr_line in ['Fruits','Vegetables', 'Meats']: 
     curr_category = curr_line  

    if curr_category != curr_line:  
     items['Category'].append(curr_category) 
     items['Item'].append(curr_line) 

df = pd.DataFrame(items).assign(key=1) 
print(df) 
#  Category  Item key 
# 0  Fruits  apple 1 
# 1  Fruits orange 1 
# 2  Fruits  pear 1 
# 3 Vegetables broccoli 1 
# 4 Vegetables squash 1 
# 5 Vegetables carrot 1 
# 6  Meats chicken 1 
# 7  Meats  beef 1 
# 8  Meats  lamb 1 

print(df['key'].groupby([df['Category'], df['Item']]).count())  
# Category Item  
# Fruits  apple  1 
#    orange  1 
#    pear  1 
# Meats  beef  1 
#    chicken  1 
#    lamb  1 
# Vegetables broccoli 1 
#    carrot  1 
#    squash  1 
# Name: key, dtype: int64 
+0

これが見事に働きました。ありがとうございました! – MBasith

1

はここでパンダを使用してforループのないソリューションです:あなたは、このようなグループ化のための数値を必要とするようキー次の出力所望の結果に使用されています。

import pandas as pd 
category = ['Fruits', 'Vegetables', 'Meats'] 

items='''Fruits 
apple 
orange 
pear 
Vegetables 
broccoli 
squash 
carrot 
Meats 
chicken 
beef 
lamb''' 

in_df = pd.DataFrame(items.splitlines()) 

グループを作成するかどうかは、その行がカテゴリにあるかどうかによって異なります。

in_df = in_df.assign(group=in_df.isin(category).cumsum()) 

cateogry果実関係

df_out = in_df.groupby('group').apply(lambda x: x[1:]).reset_index(drop = True).merge(cat_df, left_on='group', right_index=True) 

ドロップを作成、再び第1行目に各群の第二列に参加し、各グループに

cat_df = in_df.groupby('group').first() 

を最初の行からデータフレームを作成しますキーのグループ化と列名の変更

df_out = df_out.drop('group',axis=1).rename(columns={'0_x':'Fruit','0_y':'Category'}) 
print(df_out) 

出力:

 Fruit Category 
0  apple  Fruits 
1 orange  Fruits 
2  pear  Fruits 
3 broccoli Vegetables 
4 squash Vegetables 
5 carrot Vegetables 
6 chicken  Meats 
7  beef  Meats 
8  lamb  Meats 
2

用途:

  • チェックカテゴリにisinにより(法ffillfillnawhereffillによって
  • insert新しい列をマスクを作成
  • の両方で同じ値を削除カラムはboolean indexingで、最後はreset_indexでユニークなモノ強壮デフォルト指数。

category = ['Fruits', 'Vegetables', 'Meats'] 

items='''Fruits 
apple 
orange 
pear 
Vegetables 
broccoli 
squash 
carrot 
Meats 
chicken 
beef 
lamb''' 

df = pd.DataFrame({'Fruit':items.splitlines()}) 

mask = df['Fruit'].isin(category) 
df.insert(0,'Category', df['Fruit'].where(mask).ffill()) 
df = df[df['Category'] != df['Fruit']].reset_index(drop=True) 
print (df) 
    Category  Fruit 
0  Fruits  apple 
1  Fruits orange 
2  Fruits  pear 
3 Vegetables broccoli 
4 Vegetables squash 
5 Vegetables carrot 
6  Meats chicken 
7  Meats  beef 
8  Meats  lamb 

最終必要な数CategoriesFruits使用groupbysize場合:

What is the difference between size and count in pandas?

df1 = df.groupby(['Category','Fruit']).size() 
print (df1) 
Category Fruit 
Fruits  apple  1 
      orange  1 
      pear  1 
Meats  beef  1 
      chicken  1 
      lamb  1 
Vegetables broccoli 1 
      carrot  1 
      squash  1 
dtype: int64 
関連する問題