Python3:如何打印groupby.last组()?

2024-06-28 15:08:48 发布

您现在位置:Python中文网/ 问答频道 /正文

$ cat n2.txt
apn,date
3704-156,11/04/2019
3704-156,11/22/2019
5515-004,10/23/2019
3732-231,10/07/2019
3732-231,11/15/2019

$ python3
Python 3.7.5 (default, Oct 25 2019, 10:52:18) 
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd 
>>> df = pd.read_csv("n2.txt")
>>> df
        apn        date
0  3704-156  11/04/2019
1  3704-156  11/22/2019
2  5515-004  10/23/2019
3  3732-231  10/07/2019
4  3732-231  11/15/2019
>>> g = df.groupby('apn')
>>> g.last()
                date
apn                 
3704-156  11/22/2019
3732-231  11/15/2019
5515-004  10/23/2019
>>> f = g.last()

>>> for r in f.itertuples(index=True, name='Pandas'):
...     print(getattr(r,'apn'), getattr(r,'date'))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'Pandas' object has no attribute 'apn'

>>> for r in f.itertuples(index=True, name='Pandas'):
...     print(getattr(r,"apn"), getattr(r,"date"))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'Pandas' object has no attribute 'apn'

将此打印到文件的正确方法是什么?你知道吗

例如

apn, date
3704-156,11/22/2019
3732-231,11/15/2019
5515-004,10/23/2019

Tags: nameintxttruepandasdffordate
2条回答
df = pd.read_csv("n2.txt")
g = df.groupby('apn').last()
print(g.to_csv())

你想干什么就干什么。你知道吗

如果在控制台中键入g.to_csv(),它将返回一个以'apn,data,\r\n...'开头的字符串。当print函数遇到'\r\n'时,它将开始一个新行,最终按您的意愿提供输出。你知道吗

您的代码应该更改:

df = pd.read_csv("n2.txt")
g = df.groupby('apn')
f = g.last()

使用^{},因为f的输出是Series

f.to_csv(file)

或者将^{}与convert index一起使用到2列DataFrame

f.reset_index().to_csv(file, index=False)

或与^{}一起使用溶液:

df = pd.read_csv("n2.txt")
df = df.drop_duplicates('apn', keep='last')
df.to_csv(file, index=False)

在您的解决方案中,使用Index选择indexSeries

for r in f.itertuples(index=True, name='Pandas'):
    print(getattr(r,'Index'), getattr(r,'date'))
3704-156 11/22/2019
3732-231 11/15/2019
5515-004 10/23/2019

相关问题 更多 >