![](/img/trans.png)
[英]Pandas Dataframe Add a value to a new Column based on the previous row limited to the maximum value in that column
[英]Add a new column to a dataframe based on first value in row
我有这样的数据框:
>>> 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
一种方法是使用pd.to_numeric
,假设第一列中的非数字数据必须指示注释:
df = pd.read_csv('csv/10_no_headers_with_com.csv', header=None)
df['_starts_with_comment'] = pd.to_numeric(df[0], errors='coerce').isnull()
请注意,强烈建议不要使用系列中的这种混合类型。 您的前两个系列将不再支持矢量化操作,因为它们将存储在object
dtype系列中。 你失去了熊猫的一些主要好处。
更好的想法是使用csv
模块在文件顶部提取这些属性并将它们存储为单独的变量。 这是一个如何实现这一目标的例子。
您的命令有什么问题,只需分配给新列?:
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
尝试这个:
import pandas as pd
import numpy as np
df.loc[:,'_starts_with_comment'] = np.where(df[0].str.startswith(r'//'), True, False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.