python - 如何在熊猫数据框的第二行添加列标题?
问题描述
我有一个来自 pandas 的数据框,现在我想添加列名,但仅限于第二行。这是我之前输出的示例:
期望的输出:
我的代码:
data_line=open("file1.txt", mode="r")
lines=[]
for line in data_line:
lines.append(line)
for i, line in enumerate(lines):
# print('{}={}'.format(i+1, line.strip()))
file1_header=lines[0]
num_line=1
Dictionary_File1={}
Value_File1= data_type[0:6]
Value_File1_short=[]
i=1
for element in Value_File1:
type=element.split(',')
Value_File1_short.append(type[0] + ", " + type[1] + ", " + type[4])
i += 1
Dictionary_File1[ file1_header]=Value_File1_short
pd_file1=pd.DataFrame.from_dict(Dictionary_File1)
解决方案
你应该看看DataFrame.read_csv
。关键字参数允许您在header
文件中指明用于标题名称的行。
您可能可以通过以下方式做到这一点:
pd.read_csv("file1.txt", header=1)
在我的 python shell 中,我使用以下方法对其进行了测试:
>>> from io import StringIO # I use python3
>>> import pandas as pd
>>> >>> data = """Type Type2 Type3
... A B C
... 1 2 3
... red blue green"""
>>> # StringIO below allows us to use "data" as input to read_csv
>>> # "sep" keyword is used to indicate how columns are separated in data
>>> df = pd.read_csv(StringIO(data), header=1, sep='\s+')
>>> df
A B C
0 1 2 3
1 red blue green
推荐阅读
- kubernetes - `kubectl logs counter` 没有按照官方 Kubernetes 示例显示任何输出
- python - 用给定字符串列表中的整数值替换每个字符串的程序
- java - Hibernate Criteria DetachedCriteria 和子查询
- python-3.x - 如何在熊猫 df 列中分配列表值?
- ios - 如何在 iOS Swift 中基于 CLLocation 在 arkit 中画一条线?
- ansible - blockinline 模块不尊重 insertafter
- python - 使用 BeautifulSoup 的网页文本
- php - 在脚本中捕获异常调用在php中引发异常的对象的方法
- javascript - 更新兄弟/父组件的状态
- wolfram-mathematica - 将表达式微分的结果添加到字符串变量