2色のビー玉を描いて実験したところ、次のようになりました。
'Experiment Draw1,Draw2'
ie: 'Trail1 Yellow-Green'
そのため、結果をデータフレームに挿入し、3つの列(実験、最初の描画、2番目の描画)を取得したいと思います。結果を数値として結果データフレームにプロットできるように、効率的に分割するにはどうすればよいですか(つまり)
import pandas as pd
df=pd.DataFrame({'Data': ['Trail1 Yellow-Green','Sample1 Gold-Blue', 'Sample2 Silver-Gold', 'Test2 Gold-Yellow', 'Test Red-Blue'],})
df2 = df['Data'].apply(lambda x: pd.Series(x.split(' ')))
df3 = df2[1].apply(lambda x: pd.DataFrame(x.split('-')))
axis1=['Red','Orange', 'Yellow', 'Green', 'Blue', 'Gold', 'Silver']
axis2=['Red','Orange', 'Yellow', 'Green', 'Blue', 'Gold', 'Silver']
results=pd.DataFrame(index=axis1, columns=axis2)
データフレームに用語を追加する最良の方法は、for
ループと次のようなコードを使用することです。
results.ix[df3.loc['Red'], 'Blue'] = 'Y'
#For numerical values
results.ix[df3.loc['Red'], 'Blue'] = 1
str.extractメソッドを使用できます。
In [11]: s = df.Data
In [12]: res = s.str.extract("(?P<experiment>.*?) (?P<first>.*?)-(?P<second>.*)")
In [13]: res
Out[13]:
experiment first second
0 Trail1 Yellow Green
1 Sample1 Gold Blue
2 Sample2 Silver Gold
3 Test2 Gold Yellow
4 Test Red Blue
それから私はあなたが探していると思いますpivot_table
:
In [14]: res.pivot_table(values='experiment', cols='first', rows='second',
aggfunc=len, fill_value=0)
Out[14]:
first Gold Red Silver Yellow
second
Blue 1 1 0 0
Gold 0 0 1 0
Green 0 0 0 1
Yellow 1 0 0 0
同じ行と列のインデックスを再作成するには、次のようにインデックスを再作成する必要があると思います。
In [15]: _.reindex(axis1).reindex_axis(axis1, 1).fillna(0)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加