我想在一个文件中使用整数来相应地命名另一个文件中的列。例如:
文件1
3 2 3 3 3 2
文件2
0.2 0.0 0.0 1.0 0.98 0.98 0.02 0.02 0.97
0.4 0.4 0.3 2.0 0.30 0.03 0.30 0.93 0.39
File1中的第一个整数是3,因此在File2中,我想将前三列(在列0之后)指定为0_1, 0_2, 0_3
。File1中的第二个整数是2,因此将指定File2中的下两列1_1, 1_2
。
预期输出为:
time 0_1 0_2 0_3 1_1 1_2 2_1 2_2 2_3
0.2 0.0 0.0 1.0 0.98 0.98 0.02 0.02 0.97
0.4 0.4 0.3 2.0 0.30 0.03 0.30 0.93 0.39
当我按以下方式分配索引时,我最终得到的列编号都相同-有没有办法我可以实现所需的输出?
import pandas as pd
import numpy as np
import sys
file1 = "nsubs"
new = ['time']
file2 = sys.argv[1]
df = pd.read_csv(file1, sep=" ", header=None)
num = df.iloc[0].values.tolist()
for idx, item in enumerate(num):
if item == 3:
new.append(idx)
new.append(idx[2])
new.append(idx)
else:
new.append(idx)
new.append(idx)
df2 = pd.read_csv(file2, sep=" ", header=None)
df2.columns = [new]
实际输出:
time 0 0 0 1 1 2 2 2
0.2 0.0 0.0 1.0 0.98 0.98 0.02 0.02 0.97
0.4 0.4 0.3 2.0 0.30 0.03 0.30 0.93 0.39
有了数据,您实际上就不需要熊猫作为列标题了。您可以将它们读入列表,并对它们执行列表理解以获取标题。
读入文本文件,使用split函数将它们分开,然后将它们转换为整数
with open('file1.txt', 'r') as f:
column_counts = [int(i) for i in f.read().split()]
# [3, 2, 3, 3, 3, 2]
然后,您只需要创建一个简单的循环。照enumerate()
原样使用,对集合进行计数,并使用该值作为接下来几列的子集。显示了for循环用于演示,但我建议使用列表理解。
colums = ['time']
for i, n in enumerate(column_counts):
for j in range(1, n+1):
columns.append("{}_{}".format(i, j))
columns = ['time'] + ["{}_{}".format(i, j) for i, n in enumerate(column_counts) for j in range(1, n+1)]
#['time', '0_1', '0_2', '0_3', '1_1', '1_2', '2_1', '2_2', '2_3', '3_1', '3_2', '3_3', '4_1', '4_2', '4_3', '5_1', '5_2']
在您的示例中,file1
产生的列列表比更长file2
,因此一旦知道数据框需要多少列,就必须将它们切成薄片。如果数据使它们匹配,则可以columns=columns
在创建数据框时使用。
df = pd.read_csv('file2.txt', sep=" ", header=None)
df.columns = columns[:len(df.columns)]
df.set_index('time', inplace=True)
print(df)
# 0_1 0_2 0_3 1_1 1_2 2_1 2_2 2_3
# time
# 0.2 0.0 0.0 1.0 0.98 0.98 0.02 0.02 0.97
# 0.4 0.4 0.3 2.0 0.30 0.03 0.30 0.93 0.39
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句