首页 > 解决方案 > Dataframe .loc 未按预期附加行

问题描述

我正在运行将行添加到现有数据框的代码。使用以下代码:

df_tmp = df_inputfile.iloc[5:8,np.asarray(indices)[0]]  # rows 5-7 include header information
#df_tmp = pd.DataFrame({'a':[1, 2, 3], 'b':[4, 5, 6]})
print(len(df_tmp.index))
# append a row with ticker name repeated
df_tmp.loc[len(df_tmp.index),:] = 'a'
print(len(df_tmp.index))
df_tmp.loc[len(df_tmp.index),:] = 'b'
# append a row with label that was used for match
print(len(df_tmp.index))
df_tmp.loc[len(df_tmp.index),:] = 'c' # does not work
print(len(df_tmp.index))

我希望看到输出 3、4、5、6,但我看到的是 3、4、5、5。该 df_tmp.loc[len(df_tmp.index),:] = 'c'行没有附加数据!当我取消注释df_tmp = pd.DataFrame({'a':[1, 2, 3], 'b':[4, 5, 6]})时,代码会按预期运行并打印 3、4、5、6。

inputfile 数据框中的什么可能导致我尝试追加行为异常?输入文件数据帧只是从 CSV 文件中解析出来的。

标签: pythonpandasdataframe

解决方案


推荐阅读