gpt4 book ai didi

python - 根据行中的第一个值向数据框中添加新列

转载 作者:行者123 更新时间:2023-11-30 22:02:12 25 4
gpt4 key购买 nike

我有一个像这样的数据框:

>>> import pandas as pd

>>> pd.read_csv('csv/10_no_headers_with_com.csv')
//field field2
0 //first field is time NaN
1 132605 1.0
2 132750 2.0
3 132772 3.0
4 132773 4.0
5 133065 5.0
6 133150 6.0

我想添加另一个字段,说明第一个字段的第一个值是否是注释字符 //。到目前为止我有这样的事情:

# may not have a heading value, so use the index not the key
df[0].str.startswith('//')

添加具有此值的新列的正确方法是什么,以便结果类似于:

pd>>> pd.read_csv('csv/10_no_headers_with_com.csv', header=None)
0 1 _starts_with_comment
0 //field field2 True
1 //first field is time NaN True
2 132605 1 False
3 132750 2 False
4 132772 3 False

最佳答案

您的命令有什么问题,只是分配给一个新列?:

df['comment_flag'] = df[0].str.startswith('//')

或者您确实有 jpp 提到的混合类型列吗?

<小时/>

编辑:
我不太确定,但从您的评论中我得到的印象是您实际上并不需要额外的评论标志列。如果您想将没有注释的数据加载到数据框中,但仍然使用隐藏在注释标题中的字段名称作为列名称,您可能需要检查一下:
所以基于这个文本文件:

//field  field2
//first field is time NaN
132605 1.0
132750 2.0
132772 3.0
132773 4.0
133065 5.0
133150 6.0

你可以这样做:

cmt = '//'

header = []
with open(textfilename, 'r') as f:
for line in f:
if line.startswith(cmt):
header.append(line)
else: # leave that out if collecting all comments of entire file is ok/wanted
break
print(header)
# ['//field field2\n', '//first field is time NaN\n']

这样您就可以准备好用于例如的标题信息。列名称。
从第一个标题行获取名称并将其用于 pandas 导入就像

nms = header[0][2:].split()
df = pd.read_csv(textfilename, comment=cmt, names=nms, sep='\s+ ', engine='python')

field field2
0 132605 1.0
1 132750 2.0
2 132772 3.0
3 132773 4.0
4 133065 5.0
5 133150 6.0

关于python - 根据行中的第一个值向数据框中添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53860805/

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