前提
ここに質問の内容を詳しく書いてください。
Excel4ファイルtest.xlsxを作りました。
中身は
A1~D1まで1
A2~D2まで2
A3~D3まで3
A4~D4まで4
A5~D5まで5
と書かれたExcelファイルです。
そのファイルにPythonで行を差し込もうとして上手く行かないです。
カラム数が合わないとか出てますが合ってると思います。
実現したいこと
dfをdf1とdf2の二つのファイルに分けてdf1の最後にb1を差し込んでdf1を上書きしてその後df=df1+df2として上書きする。
発生している問題・エラーメッセージ
ValueError Traceback (most recent call last) Input In [2], in <cell line: 16>() 13 b1=df[2:3] 14 ###########次の行でdf1にb1を追加する ---> 16 df1.loc[c] =b1 18 print(b1) 19 print(df1) File ~\anaconda3\lib\site-packages\pandas\core\indexing.py:716, in _LocationIndexer.__setitem__(self, key, value) 713 self._has_valid_setitem_indexer(key) 715 iloc = self if self.name == "iloc" else self.obj.iloc --> 716 iloc._setitem_with_indexer(indexer, value, self.name) File ~\anaconda3\lib\site-packages\pandas\core\indexing.py:1682, in _iLocIndexer._setitem_with_indexer(self, indexer, value, name) 1679 indexer, missing = convert_missing_indexer(indexer) 1681 if missing: -> 1682 self._setitem_with_indexer_missing(indexer, value) 1683 return 1685 # align and set the values File ~\anaconda3\lib\site-packages\pandas\core\indexing.py:1998, in _iLocIndexer._setitem_with_indexer_missing(self, indexer, value) 1995 if is_list_like_indexer(value): 1996 # must have conforming columns 1997 if len(value) != len(self.obj.columns): -> 1998 raise ValueError("cannot set a row with mismatched columns") 2000 value = Series(value, index=self.obj.columns, name=indexer) 2002 if not len(self.obj): 2003 # We will ignore the existing dtypes instead of using 2004 # internals.concat logic ValueError: cannot set a row with mismatched columns
該当のソースコード
python
1import pandas as pd 2input_file_name = 'C:/Users/user_name/test.xlsx' 3input_book = pd.ExcelFile(input_file_name) 4#sheet_namesメソッドでExcelブック内の各シートの名前をリストで取得できる 5input_sheet_name = input_book.sheet_names 6input_sheet_df = input_book.parse(input_sheet_name[0]) 7global df 8df=input_sheet_df 9c=2 10df1 = df[0:c] 11df2 = df[c:] 12b1=df[2:3] 13###########次の行でdf1にb1を追加する 14 15df1.loc[c] =b1 16 17

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/01/16 00:27