pandas apply関数の練習
pandasの操作が結構複雑なので練習してみた
■会員毎の月間利用日数を集計
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import datetime, date, timedelta
from dateutil.relativedelta import relativedelta
df = pd.read_csv('./input/nyukan_data_csv.csv')
# 計算対象のカラムをdatatime型に変換
df['check'] = pd.to_datetime(df['check'])
df['join_date'] = pd.to_datetime(df['join_date'])
# 元データをコピー
df_tmp = df.copy()
#df_tmp
# 会員の入会日に合わせての1ヶ月おきの日付をカラムで持たせる(今回は10ヶ月分)
for cn in range(0, 11):
column_name = 'month_add+{}'.format(cn)
df_tmp[column_name] = df_tmp['join_date'].apply(lambda x: x + relativedelta(months=cn))
#df_tmp
# 結果格納用の変数(適当に初期化)
df_res = [[]]
# 会員毎の月間利用日数を集計
for cn in range(0, 10):
month_start = 'month_add+{}'.format(cn)
month_end = 'month_add+{}'.format(cn+1)
df_tmp_grouped = df_tmp.groupby("id").apply(lambda d: ((d['check'] >= d[month_start]) & (d['check'] < d[month_end])).sum()).reset_index()
df_tmp_grouped = df_tmp_grouped.rename(columns={0:month_end})
# print(cn)
#df_res
#df_tmp_grouped
# 列を結合
if (cn == 0):
df_res = df_tmp_grouped.copy()
else:
df_res = pd.merge(df_res, df_tmp_grouped, on='id')
# 結果
df_res
#df_grouped = df.groupby("id").apply(lambda d: (1 if (d.check >= d.join_date) & (d.check <= d.join_date + relativedelta(month=1)) else 0))
#df_grouped = df.groupby("id").filter(lambda d: (d['check'] >= d['join_date']) & (d['check'] <= d['join_date'] + relativedelta(month=1)))
#df_grouped = df.groupby("id").query('{} == "X"'.format(s))
#print(df_grouped.groups)
#df_grouped.get_group(1)
#df_grouped.describe().stack()
#df_grouped = df_grouped.apply(date_func, aaxis=1)
#df_grouped
■会員毎の月間利用時間の平均を出力(編集中…
# コピー
df_tmp = df.copy()
# 利用時間を計算
df_tmp['check'] = df_tmp['check'].apply(lambda x: x.strftime('%Y-%m-%d'))
df_tmp['start_time'] = df_tmp['start_time'].apply(lambda x: str(x))
df_tmp['end_time'] = df_tmp['end_time'].apply(lambda x: str(x))
df_tmp['start_time'] = pd.to_datetime(df_tmp['check'].str.cat(df_tmp['start_time'], sep=' '), format='%Y-%m-%d %H%M')
df_tmp['end_time'] = pd.to_datetime(df_tmp['check'].str.cat(df_tmp['end_time'], sep=' '), format='%Y-%m-%d %H%M')
df_tmp['use_time'] = df_tmp['end_time'] - df_tmp['start_time']
# df_tmp
# datatime型に戻す
df_tmp['check'] = pd.to_datetime(df_tmp['check'])
#df_tmp
# 会員の入会日に合わせての1ヶ月おきの日付をカラムで持たせる(今回は10ヶ月分)
for cn in range(0, 11):
column_name = 'month_add+{}'.format(cn)
df_tmp[column_name] = df_tmp['join_date'].apply(lambda x: x + relativedelta(months=cn))
df_tmp
# # 結果格納用の変数(適当に初期化)
# df_res = [[]]
# # 会員毎の月間利用日数を集計
# for cn in range(0, 10):
# month_start = 'month_add+{}'.format(cn)
# month_end = 'month_add+{}'.format(cn+1)
# df_tmp_grouped = df_tmp.groupby("id").apply(lambda d: ((d['check'] >= d[month_start]) & (d['check'] < d[month_end])).loc['use_time'].sum()).reset_index()
# df_tmp_grouped = df_tmp_grouped.rename(columns={0:month_end})
# # print(cn)
# #df_res
# #df_tmp_grouped
# # 列を結合
# if (cn == 0):
# df_res = df_tmp_grouped.copy()
# else:
# df_res = pd.merge(df_res, df_tmp_grouped, on='id')
# # 結果
# df_res
Azure PowerShellを使ってNSGの設定をする
■powershellインストール https://docs.microsoft.com/ja-jp/powershell/azure/install-az-ps?view=azps-5.0.0
■仮想マシン作成 https://docs.microsoft.com/ja-jp/azure/virtual-machines/windows/quick-create-powershell
■NSG作成 https://docs.microsoft.com/ja-jp/azure/virtual-network/manage-network-security-group https://docs.microsoft.com/en-us/powershell/module/az.network/new-aznetworksecurityruleconfig?view=azps-5.0.0
■受信ポート追加
$rule1 = New-AzNetworkSecurityRuleConfig -Name rdp-rule -Description "Allow RDP" `
-Access Allow -Protocol Tcp -Direction Inbound -Priority 100 -SourceAddressPrefix `
Internet -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 3389
$rule2 = New-AzNetworkSecurityRuleConfig -Name web-rule -Description "Allow HTTP" `
-Access Allow -Protocol Tcp -Direction Inbound -Priority 101 -SourceAddressPrefix `
Internet -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 80
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName TestRG -Location westus -Name `
"NSG-FrontEnd" -SecurityRules $rule1,$rule2
■送信ポート設定追加
Get-AzNetworkSecurityGroup -Name "NSG-FrontEnd" -ResourceGroupName "myResourceGroup" | Add-AzNetworkSecurityRuleConfig -Name sendmail-rule -Description "Allow SMTP" -Access Allow -Protocol Tcp -Direction Outbound -Priority 101 -SourceAddressPrefix * -SourcePortRange 25 -DestinationAddressPrefix * -DestinationPortRange * | Set-AzNetworkSecurityGroup
アルファベット順って加算で出力できるのか(今さら)
public class Hello{
public static void Main(){
char[] lines = System.Console.ReadLine().ToString().ToCharArray();
for(char moji='A'; moji<='Z'; ++moji) {
if ( moji >= lines[0] && moji <= lines[lines.Length - 1]) {
System.Console.WriteLine(moji);
}
}
}
}
public class Hello{
public static void Main(){
char[] lines = System.Console.ReadLine().ToString().ToCharArray();
for(char moji='A'; moji<='Z'; ++moji) {
if (moji.Equals(lines[0])) {
System.Console.WriteLine("true");
break;
} else if (moji.Equals(lines[lines.Length - 1])) {
System.Console.WriteLine("false");
break;
}
}
}
程よく設定したvimrc
"=============================
"
" sample setting
"
"=============================
"------------------------------
" basic setting
"------------------------------
" 行数表示
set number
" 文字コードをUTF-8
set fenc=utf-8
" バッファが編集中でもその他のファイルを開けるように
set hidden
" 入力中のコマンドをステータスに表示する
set showcmd
" インデントはスマートインデント
set smartindent
" ビープ音を可視化
set visualbell
" 括弧入力時の対応する括弧を表示
set showmatch
"vimコマンドモード時のコマンドを下に表示する
set showcmd
" ステータスラインを常に表示
"set laststatus=2
" コマンドラインの補完
set wildmode=list:longest
" シンタックスハイライトの有効化
syntax enable
" 検索文字列が小文字の場合は大文字小文字を区別なく検索する
set ignorecase
" 検索文字列に大文字が含まれている場合は区別して検索する
set smartcase
" 検索文字列入力時に順次対象文字列にヒットさせる
set incsearch
" 検索時に最後まで行ったら最初に戻る
set wrapscan
" 検索語をハイライト表示
set hlsearch
" 不可視文字を可視化(タブが「▸-」と表示される)
set list listchars=tab:\▸\-
" Tab文字を半角スペースにする
set expandtab
" 行頭以外のTab文字の表示幅(スペースいくつ分)
set tabstop=2
" 行頭でのTab文字の表示幅
set shiftwidth=2
"------------------------------
" key map setting
"------------------------------
" 行頭に移動
noremap <S-h> ^
" 固定文言を挿入する(デフォルトはphpのdebug)
noremap <S-d> ovardump("hoge");<ESC>
" 行末に移動
noremap <S-l> $
"------------------------------
" etc
"------------------------------
"全角スペースを赤で表示する
autocmd Colorscheme * highlight FullWidthSpace ctermbg=red
autocmd VimEnter * match FullWidthSpace / /
colorscheme darkblue
dictionaryのソート
Linqって便利だわ
using System;
using System.Collections.Generic;
using System.Linq;
public class Hello{
public static void Main(){
int line =int.Parse(System.Console.ReadLine());
var myTable = new Dictionary<string, int>();
for (int i = 0;i < line;i++) {
string[] line2 =System.Console.ReadLine().ToString().Split(' ');
// 同じkeyがある場合はvalueを加算する
if (myTable.ContainsKey(line2[0])) {
myTable[line2[0]] += int.Parse(line2[1]);
} else {
myTable.Add(line2[0], int.Parse(line2[1]));
}
}
//value降順でソート
IOrderedEnumerable<KeyValuePair<string, int>> sortTable = myTable.OrderByDescending(pair => pair.Value);
foreach(KeyValuePair<string, int> item in sortTable) {
Console.WriteLine("{0} {1}", item.Key, item.Value);
}
Console.ReadKey();
}
}
C# 配列を昇順で…
昇順のメモ
using System;
using System.Collections.Generic;
public class Hello{
public static void Main(){
int line = int.Parse(System.Console.ReadLine());
string[] arr = System.Console.ReadLine().ToString().Split(' ');
int[] list = new int[arr.Length];
for (int i = 0; i < arr.Length;i++) {
list[i] = int.Parse(arr[i]);
}
Array.Sort(list);
foreach (int j in list) {
System.Console.WriteLine(j);
}
}
}
C#のハッシュテーブルはこんな感じ
使いたいときの備忘
using System;
using System.Collections.Generic;
public class Hello{
public static void Main(){
int line =int.Parse(System.Console.ReadLine());
var myTable = new Dictionary<string, int>();
for (int i = 0;i < line;i++) {
string[] line2 =System.Console.ReadLine().ToString().Split(' ');
myTable.Add(line2[0], int.Parse(line2[1]));
}
foreach(KeyValuePair<string, int> item in myTable) {
Console.WriteLine("{0}", item.Value);
}
Console.ReadKey();
}
}