[英]add a row to data frame and name it
我有一個包含行 aj 的數據框,並且想要添加行 k。 當我使用 append function 時,它會添加第 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
output 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)
Output:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.