gpt4 book ai didi

python3 : how to print groupby. 最后()?

转载 作者:行者123 更新时间:2023-12-01 06:48:32 26 4
gpt4 key购买 nike

$ 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

最佳答案

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' 时会另起一行,最终按照您的意愿输出。

关于python3 : how to print groupby. 最后()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com