pythonのdataframeの結合方法について質問があります。
既存の関数では、2つのdataframeを結合する際、dataframe1のn行目にdataframe2のm行目を
挿入する関数がなさそうなので作成しました。
しかし、想定通り動かず、下記のようになります。(2回目の呼び出しの場合、新しい列が追加される)
どこを修正すれば、理想に動くでしょうか?
input
index | A | B | C |
---|---|---|---|
0 | for | one | 11 |
1 | bar | one | 12 |
2 | for | two | 13 |
index | D | E | F |
---|---|---|---|
0 | a | 101 | 16:00 |
1 | b | 102 | 9:00 |
2 | c | 103 | 12:00 |
3 | d | 104 | 21:00 |
output
1回目(想定通り)
|index|A|B|C|D|E|F|
|:--|:--:|--:|--:|
|0|for|one|11|
|1|bar|one|12|b|102|9:00|
|2|for|two|13|
2回目(想定外)
|index|A|B|C|D|E|F|D|E|F|
|:--|:--:|--:|--:|
|0|for|one|11|
|1|bar|one|12|b|102|9:00|
|2|for|two|13||||c|103|12:00|
理想
|index|A|B|C|D|E|F|
|:--|:--:|--:|--:|
|0|for|one|11|
|1|bar|one|12|b|102|9:00|
|2|for|two|13|c|103|12:00|
python
1#!/usr/bin/python3 2# -*- Coding: utf-8 -*- 3 4import pandas as pd 5 6 7# 2つのDFを結合、inputDF2のtarget_row行をinputDF1のinsert_row行に挿入する。 8def insert_data_frame(inputDF1, inputDF2, insert_row, target_row): 9 10 # 挿入行を格納 11 insert_df = pd.DataFrame(index=[target_row]) 12 insert_df = insert_df.append(inputDF2.iloc[insert_row]) 13 insert_df = insert_df.dropna(0) 14 insert_df.index = [insert_row] 15 16 # 2つのDFを結合 17 output_df = pd.concat([inputDF1, insert_df], axis = 1) 18 output_df.to_csv("test.csv") 19 20 return output_df 21 22 23def main(): 24 # 適当なDFを作成 25 df1 = pd.DataFrame({"A": ['foo', 'bar', 'foo'], 26 "B": ['one', 'one', 'two'], 27 "C": range(11, 14) 28 }) 29 30 df2 = pd.DataFrame({"D": ['a', 'b', 'c', 'd'], 31 "E": range(101, 105), 32 "F": ['16:00', '09:00', '12:00', '21:00'] 33 }) 34 35 insert_df = insert_data_frame(df1, df2, 1, 2) 36 37 #2回目想定通りの動作しない 38 insert_df = insert_data_frame(insert_df, df2, 2, 3) 39 print(insert_df) 40 41 42if __name__ == '__main__': 43 main() 44 45
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/03 12:49