1
1

More than 3 years have passed since last update.

僕のPythonの基礎だけど知らなかった

Last updated at Posted at 2019-12-17

Pythonの基礎の基礎なんだけど知らなかったことを、知った順に書き連ねていきます。

関数の引数のstarとdoublestar

関数は引数に
*(star)を付けるとタプル型の引数になり
**(double star)を付けると辞書型の引数になる
例)

def print_text(*x):
    print(x)

def print_text(**x):
    print(x)

否定論理和演算子(例えばdfで重複行を消す時)

df = df[~df.duplicated()]

listに要素を追加

#どっちでも大丈夫
list1.extend(list2)
list1 = list1 + list2

#でもこれはエラーになる
list1 = list1.extend(list2)


map

これはかなりよく使う

###例えば、forみたいな感じでリストを作るとき###

def plus_one(i):
    return i+1

list1 = [1,2,3]
  #mapの戻り値はイテレーターだからlistで囲ってやって
list2 = list(map(puls_one,list1))
    #list2 = [2,3,4]

#ラムダ式使ってもOK
#ラムダ.ver
list2 = list(map(lambda x : x+1,list1))

データフレームのある列に加工したり、追加したりする時
for index, item in df.iterrows()
で回すとめちゃくちゃ時間がかかる(Seriesの生成回避とかある程度の対策をしても)。

そうじゃなくて、一旦
list = list(map(func,index_list))
で突っ込みたい列をリストで作っておいて、後から
df.assign(new_low = list)
の方が、ずっと速い。

4000万行のdfで実行した経験から、そう思う(笑)

1
1
0

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
1
1