Python - Panda 在某个条件下将 csv 拆分为多个文件

时间:2021-07-09 13:45:34

标签: python pandas dataframe

我有一个看起来像这样的 csv:

import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Layouts 1.0

Window {
    id: window
    width: 300
    height: 300
    color: "black"
    visible: true

    RowLayout {
        id: root

        Text {
            id: txt
            text: "t2"
            font.pixelSize: window.height / 4
            color: "white"
            Layout.alignment: Qt.AlignBaseline //<=======

            Text {
                text: "t1"
                font.pixelSize: window.height / 4
                color: "white"
                anchors.bottom: parent.top
            }
        }
        Text {
            id: txt3
            text: "t3"
            Layout.alignment: Qt.AlignBaseline //<=======
            font.pixelSize: window.height / 1.5
            color: "white"
        }
    }
}

每次最后一列的数字减少时,我想拆分数据框并保存到新文件中 输出将如下所示:
文件 1:

'-'  'd'  '5'
'-'  'd'  '9'
'-'  'v'  '15'
'-'  's'  '8'
'-'  's'  '10'
'-'  'q'  '3'

文件 2

'-'  'd'  '5'
'-'  'd'  '9'
'-'  'v'  '15'

文件 3

'-'  's'  '8'
'-'  's'  '10'

3 个答案:

答案 0 :(得分:1)

为简单起见,我将假设您的 CSV 文件看起来像典型的 CSV 文件:

-,d,5
-,d,9
...

我还假设最后一列中的数字始终为正整数。

prev = 0
accumulatedLines = []
decreasedCount = 0
with open("my_file.txt", "r") as fin:
    for line in fin:
        values = line.split(",")
        if int(values[2]) < prev:
            with open("File{}.txt".format(decreasedCount + 1), "w") as fout:
                fout.writelines(accumulatedLines)
            decreasedCount += 1
            accumulatedLines = []

        accumulatedLines.append(line)
        prev = int(values[2])

本质上,我们遍历输入文件中的每一行,用逗号分隔符将其拆分,并跟踪上一行最后一列的值。我们还将读取的行累积到当前行。如果最后一列中当前行的值严格小于前一行的值,我们将累积的行写入一个新文件(以迄今为止我们遇到递减值的次数命名)。然后我们清除累加器(并增加计数)。

答案 1 :(得分:0)

使用 Series.shift 可以比较相邻的行。

from io import StringIO
import pandas as pd

s = """'-'  'd'  '5'
'-'  'd'  '9'
'-'  'v'  '15'
'-'  's'  '8'
'-'  's'  '10'
'-'  'q'  '3'""".replace("'", "")
df = pd.read_csv(StringIO(s), sep="\s\s+", engine="python", names=["a", "b", "c"])

# preserve the original column names
cols = df.columns
# create a grouping column
df["d"] = (df["c"].shift(fill_value=0) > df["c"]).cumsum()

# output each group
for name, group in df.groupby("d"):
    group[cols].to_csv(f"output_{name}.csv", index=False)

产生这些组:

   a  b   c
0  -  d   5
1  -  d   9
2  -  v  15
-----------
   a  b   c
3  -  s   8
4  -  s  10
-----------
   a  b  c
5  -  q  3
-----------

答案 2 :(得分:0)

  1. 阅读 CSV:
df = pd.read_csv(
    "your_file.txt",
    quotechar="'",
    quoting=1,
    sep=r"\s+",
    header=None,
)
  1. 打印组:
for _, g in df.groupby(df[2].diff().le(0).cumsum()):
    print(g.to_csv(index=None, quotechar="'", quoting=1, sep=" ", header=None))

注意:要写入文件,请将文件名添加到 .to_csv()。如果没有文件名,它会将组写入屏幕。


打印:

'-' 'd' '5'
'-' 'd' '9'
'-' 'v' '15'

'-' 's' '8'
'-' 's' '10'

'-' 'q' '3'

相关问题