合并具有相同行长和不同列号的多个无头csv文件

2024-10-01 15:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

作为这篇文章的标题,我在网上发现的主要是和标题合并。浏览只会给我这个唯一可以返回结果的代码

import pandas as pd
import glob
interesting_files = glob.glob("*.csv")
df_list = []
for filename in sorted(interesting_files):
    df_list.append(pd.read_csv(filename))
full_df = pd.concat(df_list)

full_df.to_csv('output.csv')

` 但结果一点也不好,如图所示: enter image description here

我想要的就是这样 enter image description here

编辑 我发现这个对我的案子真的很有用

import pandas as pd
import glob
import csv

interesting_files = glob.glob("*.csv")
df_list = []
for filename in sorted(interesting_files):
    df_list.append(pd.read_csv(filename, header=None))
full_df = pd.concat(df_list, ignore_index=True, axis=1)
        
full_df.to_csv('Route_data.csv') #,header = ['a','b',...], index=False) for csv output header index=False)

删除刚刚合并的旧文件的附加代码使其功能更加强大


Tags: csv代码import标题dfforindexfiles
1条回答
网友
1楼 · 发布于 2024-10-01 15:35:31

您可以使用:

pd.concat([df1, df2], axis=1)

例如:

import pandas as pd
df1 = pd.DataFrame([*zip([1,2,3],[4,5,6])])
print(df1)
df2 = pd.DataFrame([*zip([7,8,9],[10,11,12])])
print(df2)
df_combined = pd.concat([df1, df2], axis=1)
print(df_combined)

输出:

df1>
   0  1
0  1  4
1  2  5
2  3  6

df2>
   0   1
0  7  10
1  8  11
2  9  12

df_combined>
   0  1  0   1
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12

数据帧示例:

import pandas as pd
df1 = pd.read_csv("/path/file1.csv", header=None)
print(df1)
df2 = pd.read_csv("/path/file2.csv", header=None)
print(df2)
df_combined = pd.concat([df1, df2], axis=1)
print(df_combined)

相关问题 更多 >

    热门问题