将一行添加到数据框中并命名它

问题描述 投票:0回答:1

我有一个数据行,其中包含a-j行,并想添加k行。当我使用append函数时,它会添加第k行,但其他行周围有(),即(a),(b)等。有人知道如何将那些()移出吗?1中的代码:

import pandas as pd
import numpy as np
from pandas import Series, DataFrame

data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake','cat', 'dog', 'dog'], 
    'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3], 
    'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 
    'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=[labels])
df

代码2:

df.loc['k'] = ['lion', 1, 3, 'yes']
df

输出2:

     animal  age  visits priority
(a,)    cat  2.5       1      yes
(b,)    cat  3.0       3      yes
(c,)  snake  0.5       2       no
(d,)    dog  NaN       3      yes
(e,)    dog  5.0       2       no
(f,)    cat  2.0       3       no
(g,)  snake  4.5       1       no
(h,)    cat  NaN       1      yes
(i,)    dog  7.0       2       no
(j,)    dog  3.0       1       no
k      lion  1.0       3      yes
python dataframe append rows
1个回答
0
投票

:添加到df.loc

df.loc['k', :] = ['lion', 1, 3, 'yes']
print(df)

输出:

  animal  age  visits priority
a    cat  2.5     1.0      yes
b    cat  3.0     3.0      yes
c  snake  0.5     2.0       no
d    dog  NaN     3.0      yes
e    dog  5.0     2.0       no
f    cat  2.0     3.0       no
g  snake  4.5     1.0       no
h    cat  NaN     1.0      yes
i    dog  7.0     2.0       no
j    dog  3.0     1.0       no
k   lion  1.0     3.0      yes
© www.soinside.com 2019 - 2024. All rights reserved.