Python csv 将几列合并到一个单元格



如何将几列合并到一个单元格中? 如何将包含 1 x X 单元格的 CSV 文件(其中 1 是行计数,X 是用户未标记的列计数(转换为包含单个单元格的新 CSV 文件以合并原始 CSV 文件中的所有数据?

右 now://One 行,四列 ######In 事实上,当数据是从日志文件中提取的###

1 A   B  C   D   

我的目的://一行,一列

1 A
B
C
D

该行的索引可能并不总是 1,因为我有很多类似的行。

有关详细信息,请参阅以下URL中的原始文件和预期的新文件 https://drive.google.com/drive/folders/1cX0o86nbLAV5Foj5avCK6E2oAvExzt5t

161.csv is the file at the present
161-final.csv is what I want...

行数不会更改。但是,列计数是一个变量,因为数据是从日志文件中提取的。最后,我只需要每行只有一列。

我只是一个有熊猫的新鲜人。我会计算列数然后将其合并到一个单元格中吗?

非常感谢您的帮助。

代码:

import pandas as pd
import numpy as np
df = pd.DataFrame([['a', 'a', 'a', 'a'], ['b', 'b', 'b', 'b']])
print(df)
df1 = np.empty(df.shape[0], dtype=object)
df1[:] = df.values.tolist()
print(df1)

输出:

0  1  2  3
0  a  a  a  a
1  b  b  b  b
[list(['a', 'a', 'a', 'a']) list(['b', 'b', 'b', 'b'])]

不确定这是您想要的,但您可以设法将一行的内容放在一列中,并pd.groupby()

import pandas as pd
df = pd.DataFrame(np.arange(4).reshape(1, 4))
df.columns = ['A', 'B', 'C', 'D']
df = df.groupby(df.index).apply(lambda x: x.values.ravel())
df = df.to_frame('unique_col') # If needed

输出:

unique_col
0  [0, 1, 2, 3]

不确定这是否可能不在列表中,正如您在示例中提到的那样。

我用了一种"愚蠢"的方式来做到这一点。它是"pd.read_table(文件("做魔术。

def CsvMerge(file1, file2,output):
##It is for preparation of the getFormated()
##Merge the "Format.csv" and the "text.csv.csv
df1=pd.read_csv(file1)
###This is for merging the columns to one column
###It can also avoid an csv error
df2=pd.read_table(file2)
df3=pd.concat([df1,df2],axis=1)
print(df3)
with open(output,'w+',encoding="utf-8") as f:
df3.to_csv(f,index=False)
f.close()

相关内容

最新更新