在python pandas中展平索引

时间:2017-07-27 08:26:26

标签: python pandas dataframe

我是python的新手,我一直在玩Panda数据帧,但是当我使用groupby时,我不再能够使用标签迭代数据帧。

有人可以帮助我吗?

newDF=df[df['Currency'].str.contains(currency)&df['Description'].str.contains('fx')]
newDF=newDF.rename(index=str, columns={ "Paid": "Withdrawn"})

moneyWithdrawnByUserDF=pd.DataFrame(newDF.groupby(['FirstName'])[['Withdrawn']].sum())

for index,row in moneyWithdrawnByUserDF.iterrows():
  print row['FirstName']

我得到的输出/错误如下:

Index([u'Email', u'FirstName', u'LastName', u'Owed', u'Withdrawn', u'UserId',

Traceback (most recent call last):

File "main.py", line 416, in <module>

sys.exit(main(sys.argv[1:]))

File "main.py", line 412, in main

parseGroups()

   u'Category', u'Description', u'Id', u'Currency', u'Cost', u'Details',

   u'GroupId'],

  dtype='object')

 File "main.py", line 45, in parseGroups

parseGroup(group) 

  File "main.py", line 81, in parseGroup processCurrencies(df)

  File "main.py", line 95, in processCurrencies processCurrency(df, currency)

  File "main.py", line 105, in processCurrency   moneyWithdrawnByUserDF=calculateMoneyWithdrawnByUser(df, currency)

 File "main.py", line 319, in calculateMoneyWithdrawnByUser

print row['FirstName']

 File "/usr/local/lib/python2.7/site-packages/pandas/core/series.py", line 601, in __getitem__

result = self.index.get_value(self, key)

 File "/usr/local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2491, in get_value

  raise e1

 KeyError: 'FirstName'

谢谢

1 个答案:

答案 0 :(得分:1)

我认为你需要改变:

moneyWithdrawnByUserDF=pd.DataFrame(newDF.groupby(['FirstName'])[['Withdrawn']].sum())

reset_index

moneyWithdrawnByUserDF= newDF.groupby(['FirstName'])['Withdrawn'].sum().reset_index()

as_index=False的参数DataFrame

moneyWithdrawnByUserDF= newDF.groupby(['FirstName'], as_index=False)['Withdrawn'].sum()