我制作了一个数据框,其中包含我认识的人,他们与我的关系以及他们的生日月份。我想和妈妈一起在这个数据框中添加一个新系列。
import pandas as pd
entry_one = pd.Series({'Name':'Ryan',
'Relationship':'Self',
'Birthday_Month' : 'April'})
entry_two = pd.Series({'Name':'Nickie',
'Relationship': 'Girlfriend',
'Birthday_Month':'February'})
entry_three = pd.Series({'Name':'Jeff',
'Relationship':'Friend',
'Birthday_Month':'August'})
entry_four = pd.Series ({'Name':'Mica',
'Relationship':'Friend',
'Birthday_Month':'November'})
entry_five = pd.Series ({'Name':'Andrew',
'Relationship':'Friend',
'Birthday_Month':'November'})
df = pd.DataFrame([entry_one, entry_two, entry_three, entry_four, entry_five])
df = df.set_index('Name')
df
df.append(pd.Series(data = ('Name':'Mom','Relationship':'Mother','Birthday_Month':'May')))
但是我收到了错误
错误
文件“”,第1行 df.append(pd.Series(data =('Name':'Mom','Relationship':'Mother','Birthday_Month':'May'))) ^ SyntaxError:语法无效
我在这里做错了什么?
答案 0 :(得分:1)
你在最后一行使用了错误的括号类型,它需要是一个字典,你需要打开忽略)索引能够像这样追加:
df.append(pd.Series(data = {'Name':'Mom','Relationship':'Mother','Birthday_Month':'May'}), ignore_index=True)
答案 1 :(得分:0)
您需要dictionary
不Name
,它用作name
的参数Series
:
df = pd.DataFrame([entry_one, entry_two, entry_three, entry_four, entry_five])
df = df.set_index('Name')
df = df.append(pd.Series(data = {'Relationship':'Mother','Birthday_Month':'May'},name='Mom'))
无变化的动态解决方案dictionary
,仅过滤掉Name
并按name of Series
选择key of dict
:
d = {'Name':'Mom','Relationship':'Mother','Birthday_Month':'May'}
df = df.append(pd.Series(data = {k:v for k,v in d.items() if k!= 'Name'},name=d['Name']))
print (df)
Birthday_Month Relationship
Name
Ryan April Self
Nickie February Girlfriend
Jeff August Friend
Mica November Friend
Andrew November Friend
Mom May Mother
或者在DataFrame.append
中使用ignore_index=True
而不使用set_index
:
df = pd.DataFrame([entry_one, entry_two, entry_three, entry_four, entry_five])
d = {'Name':'Mom','Relationship':'Mother','Birthday_Month':'May'}
df = df.append(pd.Series(data=d), ignore_index=True)
print (df)
Birthday_Month Name Relationship
0 April Ryan Self
1 February Nickie Girlfriend
2 August Jeff Friend
3 November Mica Friend
4 November Andrew Friend
5 May Mom Mother