LoginSignup
0

More than 1 year has passed since last update.

一つのレコードから複数の列を新たに追加

Posted at

概要

データの処理の際にレコード内に4つの情報が入っていてそれを取り出す必要があったので備忘録として記録しておきます。(前回はJSONフォーマットでしたが今回は半角スペース区切りでデータが入力されていることが前提)

id Jan Feb
1 1位 大阪府 12,345 67% 1位 大阪府 11,111 22%
2 2位 京都府 98,765 43% 2位 京都府 22,222 33%

こんな感じで空白区切りでレコード内にデータがいくつか入っているものを

id 1月順位 都道府県 割合 2月順位 都道府県 割合
1 1位 大阪府 12,345 67% 1位 大阪府 11,111 22%
2 2位 京都府 98,765 43% 2位 京都府 22,222 33%

こんな感じにするのがゴール

コード

データフレームの作成

import pandas as pd 

dict1=dict(Jan=["1位 大阪府 12,345 67%","2位 京都府 98,765 43%"],Feb=["1位 大阪府  11,111 22%","2位 京都府 22,222 33%"])
list1=pd.DataFrame(data=dict1)
list1

splitを利用して元のデータフレームに列を追加

cols_name=['Jan','Feb']

list_new =[]
list_split=[]

for i in cols_name:
  list_split=list1[i].str.split(' ',expand=True)
  list_spilit_1=list_split.values.tolist()
  list_new.append(list_spilit_1)

df_list=[]

for i in range(len(list1.columns)):
  list_new_new=list_new[1-i]
  new_new=pd.DataFrame(list_new_new)
  df_list.append(new_new)
  new_df=pd.concat(df_list,axis=1)

new_df

列名が「0」「1」「2」「3」みたいに数字になってしまい、それも列追加の際に「順位」「都道府県」みたいにできれば良かったんですが実力不足でできませんでした。。。
なのでかっこ悪いですがこの処理の後にrenameで列名を変えました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0