我正在尝试使用特定索引名称“e”向DataFrame添加新行.
number variable values
a NaN bank true
b 3.0 shop false
c 0.5 market true
d NaN government true
我尝试了以下但是它创建了一个新列而不是一个新行.
new_row = [1.0, 'hotel', 'true']
df = df.append(new_row)
仍然不明白如何插入具有特定索引的行.将不胜感激任何建议.
解决方法:
您可以使用df.loc [_not_yet_existing_index_label_] = new_row.
演示:
In [3]: df.loc['e'] = [1.0, 'hotel', 'true']
In [4]: df
Out[4]:
number variable values
a NaN bank True
b 3.0 shop False
c 0.5 market True
d NaN government True
e 1.0 hotel true
PS使用此方法无法添加已存在(重复)索引值(标签)的行 – 在这种情况下,将更新具有此索引标签的行.
更新:
This might not work in recent Pandas/Python3 if the index is a
DateTimeIndex and the new row’s index doesn’t exist.
如果我们指定正确的索引值,它将起作用.
演示(使用熊猫:0.23.4):
In [17]: ix = pd.date_range('2018-11-10 00:00:00', periods=4, freq='30min')
In [18]: df = pd.DataFrame(np.random.randint(100, size=(4,3)), columns=list('abc'), index=ix)
In [19]: df
Out[19]:
a b c
2018-11-10 00:00:00 77 64 90
2018-11-10 00:30:00 9 39 26
2018-11-10 01:00:00 63 93 72
2018-11-10 01:30:00 59 75 37
In [20]: df.loc[pd.to_datetime('2018-11-10 02:00:00')] = [100,100,100]
In [21]: df
Out[21]:
a b c
2018-11-10 00:00:00 77 64 90
2018-11-10 00:30:00 9 39 26
2018-11-10 01:00:00 63 93 72
2018-11-10 01:30:00 59 75 37
2018-11-10 02:00:00 100 100 100
In [22]: df.index
Out[22]: DatetimeIndex(['2018-11-10 00:00:00', '2018-11-10 00:30:00', '2018-11-10 01:00:00', '2018-11-10 01:30:00', '2018-11-10 02:00:00'], dtype='da
tetime64[ns]', freq=None)
标签:python,pandas,dataframe