Skip to main content
 首页 » 编程设计

python之让 Pandas 设置正确

2025年05月04日28mfryf

从 0.13 版本开始,可以通过引用 .loc 或 .ix 中尚不在数据框中的索引来附加到数据框中。查看documentation .

然后我很困惑为什么这条线失败了:

all_treatments.loc[originalN:newN,:]    = all_treatments.loc[0:newrowcount,:] 

这会产生一个 ValueError:

ValueError: could not broadcast input array from shape (12) into shape (0) 

此处 all_treatments.shape = (53, 12), originalN = 53, newN = 64, all_treatments.loc[ originalN:newN,:].shape = (0,12), all_treatments.loc[0:newrowcount,:].shape = (12,12).

这里设置放大的正确方法是什么?

请您参考如下方法:

只能对单行或单列进行放大设置。您正在设置一个范围。

The .loc/.ix/[] operations can perform enlargement when setting a non-existant key for that axis.

为了您的使用,像这样的东西应该可以用新的空白行扩展数据框:

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) 
>>> df 
    a   b 
0   1   4 
1   2   5 
2   3   6 
 
new_row_count = 2 
for new_row, old_row in enumerate(range(new_row_count), start=len(df)): 
    df.ix[new_row] = None 
 
>>>df 
    a   b 
0   1   4 
1   2   5 
2   3   6 
3   NaN NaN 
4   NaN NaN 

如果您想从原始数据框中复制数据,我通常只是连接。

df = pd.concat([df, df.iloc[:2, :]], ignore_index=True)