1
私がいる入力テキストファイル:pandasを使用してテキストファイルからキー、値を分割する方法は?このような
Input.txt-
1=88|2=1438|3=KKK|4=7.7|5=00|7=66|8=a
1=13|2=1388|3=DDD|4=157.73|6=00|7=08|8=b|9=k
私はこのキーと値のペアを分割したいと、このような形式で表示:
インデックスで参照Output.txt-
index[0]
1 88
2 1438
3 kkk
4 7.7
5 00
6
7 66
8 a
9
index[1]
1 13
2 1438
3 DDD
4 157.73
5
6 00
7 08
8 b
9 k
[0] 6と9番目のレコードの値は空白です.6は他の列で使用できますが、これは使用できないためです。 index [1]のように、5番目のレコードは空白です。
プログラム・コード -
df = pd.read_csv(inputfile, index_col=None, names=['text'])
#spliting two times with respect to (= & |) and saving into stack
s = df.text.str.split('|', expand=True).stack().str.split('=', expand=True)
#giving index's as empty string ('') i.e. for removing
s.columns = ['idx','']
#rename_axis(None) for excluding index values
dfs = [g.set_index('idx').rename_axis(None) for i, g in s.groupby(level=0)]
#length for iterating through list
dfs_length = len(dfs)
#opening output file
with open(outputfile + 'output.txt','w') as file_obj:
i = 0
while i < dfs_length:
#index of each column
s = '\nindex[%d]\n'%i
#writing index to file
file_obj.write(str(s))
#print '\nindex[%d]'%i
#print dfs[i]
#wriring actual contents to file
file_obj.write(str(dfs[i])+'\n')
i = i + 1
私はこの出力を取得しています:
output.txt-
index[0]
1 88
2 1438
3 kkk
4 7.7
5 00
7 66
8 a
index[1]
1 13
2 1438
3 DDD
4 157.73
6 00
7 08
8 b
9 k
私はレコードがどのていることだけを取得しています入力テキストファイルで利用可能です。レコードの価値を空白にするにはどうすればいいですか?
pat = r'(?:1=)?(?P<a1>[^\|]*)?'
# you may want to adjust the right bound of the range interval
for i in range(2, 12):
pat += r'(?:\|{0}=)?(?P<a{0}>[^\|]*)?'.format(i)
new = df.val.str.extract(pat, expand=True)
テスト:あなたが発生した正規表現と一緒に.str.extract()
機能を使用してそれを行うことができます
は宿題のように見えます。 –
@ErnestTen、そうではありません。 IMO、面白い質問です... – MaxU
@kitty、固定数の属性( '1 = ...'、...、 '9 = ...')がありますか? – MaxU