如何在CSV文件中向上移动数据

mkshixfv  于 7个月前  发布在  其他
关注(0)|答案(4)|浏览(75)

我有一个CSV文件,它可以打印这样的数据:
| 名称|点|类型|
| --|--|--|
| Name1|||
| Name2|||
| Name3|||
| | 4.5 ||
| | 2.5 ||
| | 1.0 ||
| | | type1 |
| | | type1 |
| | | type1 |
我希望它像这样打印:
| 名称|点|类型|
| --|--|--|
| Name1| 4.5| type1|
| Name2| 2.5| type1|
| Name3| 1.0| type1|
唯一的缺点是,该文件有许多这样的序列,所有这些序列都以不同的长度变化,即:
| 名称|点|类型|
| --|--|--|
| Name1|||
| Name2|||
| | 1.0 ||
| | 2.0 ||
| | | type1 |
| | | type1 |
| Name3|||
| | 4.5 ||
| | | type2 |
如何创建一个python程序,使数据向上移动到最上面的空列?
我是realitivly新的使用csv文件和编程一般所以我没有在任何尝试非常成功.我一直在使用ChatGPT,它吐出了一些建议使用Pandas和其他东西,但他们都没有解决我的问题.任何帮助是appreicated,谢谢!

w6mmgewl

w6mmgewl1#

我认为您可以使用python内置功能通读csv文件,但在单独的列表中跟踪每列中的值

import csv

cols = [[], [], []]
with open('test.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        for i in range(len(row)):
            if row[i] != '':
                cols[i].append(row[i])
        

for i in range(len(cols[0])):
    print(','.join([cols[j][i] for j in range(3)]))

字符串
如果愿意,还可以将上面的列值列表转换为pandas框架

import pandas as pd
for i in range(len(cols[0])):
    print(','.join([cols[j][i] for j in range(3)]))

eblbsuwk

eblbsuwk2#

解决这个问题的一个可能方法是使用Python中的pandas库,它可以轻松地操作 Dataframe 。下面是一个可能适合你的示例代码:
Import pandas导入pandas作为pd
读取csv文件df = pd.read_csv(“yourfile.csv”)
定义一个函数将值上移到最上面的空列def shift_up(df):
循环遍历df中col的列。columns:#查找列中第一个非空单元格的索引first_non_empty = df[col].first_valid_index()#如果索引不为零,则在first_non_empty!= 0的情况下将值上移该数量:df[col] = df[col].shift(-first_non_empty)
返回修改后的 Dataframe return df
将函数应用于 Dataframe df = shift_up(df)
将修改后的 Dataframe 写入新的csv文件df.to_csv(“newfile.csv”,index=False)
你可以在这个网站上找到更多关于Pandas及其方法的信息。我希望这对你的任务有帮助。

zqdjd7g9

zqdjd7g93#

Pandas丢弃NaN的能力使这一点变得简单。

#! /usr/bin/env python

from io import StringIO, TextIOWrapper

import pandas as pd

csv_input = """
Name,Points,Type
name1,,
name2,,
name3,,
,4.5,
,2.5,
,1.0,
,,type1
,,type1
,,type1
"""

def shift_upwards(in_file: TextIOWrapper) -> list:
    in_df = pd.read_csv(in_file)
    return pd.DataFrame(
        {col: in_df[col].dropna().reset_index(drop=True)
        for col in in_df.columns}
    )

if __name__ == "__main__":
    print(shift_upwards(StringIO(csv_input)))

字符串
产出:

Name  Points   Type
0  name1     4.5  type1
1  name2     2.5  type1
2  name3     1.0  type1

inkz8wg9

inkz8wg94#

您可以使用zip将列转置为行,并使用filter函数过滤掉空值,然后使用zip将行转置回列:

import csv
import sys
from functools import partial
from io import StringIO

file = StringIO('''Name,Points,Type
name1,,
name2,,
name3,,
,4.5,
,2.5,
,1.0,
,,type1
,,type1
,,type1''')

csv.writer(sys.stdout).writerows(
    zip(*map(partial(filter, None), zip(*csv.reader(file))))
)

字符串
这将产生:

Name,Points,Type
name1,4.5,type1
name2,2.5,type1
name3,1.0,type1

相关问题