向数据框添加一行并命名
add a row to data frame and name it
我有一个包含行 a-j 的数据框,我想添加行 k。当我使用追加函数时,它添加了第 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
将:
添加到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
我有一个包含行 a-j 的数据框,我想添加行 k。当我使用追加函数时,它添加了第 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
将:
添加到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