gpt4 book ai didi

python - 将 Header 和 Dataframe 放入新的 CSV 中

转载 作者:行者123 更新时间:2023-11-28 18:14:31 26 4
gpt4 key购买 nike

您将如何在 Panda 中定义 CSV 格式的标题。然后在分析数据后将其推送到一个新文件中。您将如何将 header 包含到新的 CSV 文件中

输入:

John Apple <-- Header Start
9/21/2005
Duration: 00:00:06 <-- Header End

Time Body_Temp Thermistor <-- Index
00:00:00 0.00
00:00:01 88.07
00:00:02 88.07
00:00:03 83.90
00:00:04 104.35
00:00:05 85.43
00:00:06 85.43

输出文件:

John Apple <-- Header Start
9/21/2005
Duration: 00:00:06 <-- Header End

Time Body_Temp Thermistor <-- Index
00:00:00 0.00
00:00:01 88.07
00:00:02 88.07
00:00:03 83.90
00:00:04 104.35 <--Points this is above 100
00:00:05 85.43
00:00:06 85.43

到目前为止我的代码:

from pandas import DataFrame, read_csv
import csv
import pandas as pd
import numpy as np

file = r'Alpha.csv'
df = pd.read_csv(file)
uncommon = df.loc[(df['Temp'] >= 100)]
#can only figure out to find any temp above 100 and print it into a new CSV
uncommon.to_csv('Dummy.csv',sep='\t')

最佳答案

如果我理解正确的话,像这样的东西应该可以工作:

file = r'Alpha.csv'
meta = pd.read_csv(file, nrows=4, header=None)
df = pd.read_csv(file, skiprows=4)
uncommon = df.loc[(df['Temp'] >= 100)]

with open('Dummy.csv', 'w') as out:
meta.to_csv(out, index=False, header=False)
uncommon.to_csv(out, sep='\t', index=False)

解释

  • 将您的元数据读入 meta 并将实际数据读入 data 数据帧。
  • data 执行操作并分配给 uncommon
  • 通过 Python 内置的 open 函数将 metauncommon 分别写入一个 csv 文件。

替代工作流程

但我的偏好是保持您的数据干净。例如,为什么不单独存储一个表,并将元数据链接到文件名?

您当前的方法将阻止您对元数据进行任何有意义的分析。

关于python - 将 Header 和 Dataframe 放入新的 CSV 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350370/

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