文字列の扱いを身近な例で学びます。
例えば、クラスのメンバーの名と得点を次のようにメモしたとします。
aa60
bb70
cc80
dd90ee100
これを読み込んで集計できるようにデータ・フレームを作成します。
まず、複数行の文字列をarrayとして読み込みます。
# stringのarrayを作成
string = """
aa60
bb70
cc80
dd90
ee100"""
print(string)
##
## aa60
## bb70
## cc80
## dd90
## ee100
行ごとに分けてリストを作成します。
# split string by line breaks
chunks = string.split('\n')
print(chunks)
## ['', 'aa60', 'bb70', 'cc80', 'dd90', 'ee100']
文字と数字が並んだstringを文字と数字に分ける関数を作成します。
スクリプトは次に解説されています。
https://stackoverflow.com/questions/35107527/python-simple-batch-rename-files-in-windows-folder
def mysplit(s):
head = s.rstrip('0123456789')
tail = s[len(head):]
return head, tail
関数を試します。
mysplit('aa60')
## ('aa', '60')
List comprehensionでchunks(リスト)からアルファベットと数字のtupleのリストを作成します。
list_of_tuples = [mysplit(i) for i in chunks]
list_of_tuples
## [('', ''), ('aa', '60'), ('bb', '70'), ('cc', '80'), ('dd', '90'), ('ee', '100')]
データ・フレームを作成します。
import pandas as pd
df = pd.DataFrame(list_of_tuples, columns = ['name', 'score'])
df.drop(df.index[0], inplace = True)
df
## name score
## 1 aa 60
## 2 bb 70
## 3 cc 80
## 4 dd 90
## 5 ee 100