python以dataframe格式读取文件夹内所有CSV文件,并将所有dataframe合并,同时只保留相同列名的数据
时间: 2024-05-05 07:18:42 浏览: 102
你好!对于你的问题,可以使用 pandas 库来读取所有 CSV 文件并合并为一个 dataframe,代码如下:
```python
import pandas as pd
import glob
path = 'path/to/folder/*.csv'
all_files = glob.glob(path)
# 读取所有CSV文件并合并
df = pd.concat((pd.read_csv(f) for f in all_files))
# 只保留相同列名的数据
df = df.reindex(columns=df.columns.intersection(df.iloc[:,0].dropna().unique()))
print(df)
```
这段代码首先使用 glob 库获取文件夹中所有的 CSV 文件路径,然后使用 pandas 库中的 concat 函数将所有 CSV 文件的数据合并。最后使用 reindex 函数只保留相同列名的数据。
希望对你有帮助!
相关问题
python将dataframe格式的txt文件转为csv文件
在Python中,如果你有一个DataFrame并想将其保存为CSV文件,可以使用pandas库来完成这个操作。pandas是一个强大的数据处理库,它提供了一个名为`to_csv()`的方法,用于将DataFrame转换成CSV文件。
以下是一个简单的例子:
```python
import pandas as pd
# 假设df是你已经加载到内存中的DataFrame
if 'df' in locals() or 'df' in globals(): # 如果df已经存在
df.to_csv('output.csv', index=False) # 将df保存为'output.csv',index=False参数表示不保留索引
else:
# 如果df不存在,你需要先读取txt文件
df = pd.read_csv('input.txt') # 假设输入文件是txt格式
df.to_csv('output.csv', index=False)
```
这里假设输入的txt文件是DataFrame的结构,并且可以直接读取。如果txt文件不是标准的CSV格式,可能需要先通过`read_csv`或自定义方法将其转换为DataFrame。
python,dataframe批量读取某一文件夹下的所有csv文件
可以使用 pandas 库中的 glob 函数来实现批量读取某一文件夹下的所有 csv 文件。具体代码如下:
```python
import pandas as pd
import glob
path = r'path/to/folder' # 文件夹路径
all_files = glob.glob(path + "/*.csv") # 获取文件夹下所有 csv 文件的路径
dfs = [] # 存储所有读取的 csv 文件的 DataFrame
for filename in all_files:
df = pd.read_csv(filename, index_col=None, header=0)
dfs.append(df)
# 将所有 DataFrame 合并为一个大的 DataFrame
df = pd.concat(dfs, axis=0, ignore_index=True)
```
其中,`path` 变量需要替换为实际的文件夹路径。`glob.glob` 函数会返回一个列表,其中包含了所有符合指定模式的文件路径。在上面的代码中,我们使用了 `pd.read_csv` 函数来读取每个 csv 文件,并将它们存储在一个列表中。最后,我们使用 `pd.concat` 函数将所有 DataFrame 合并为一个大的 DataFrame。
阅读全文
相关推荐














