python 数据框水平附加列
python dataframe appending columns horizontally
我正在尝试制作一个简单的脚本,用于连接或附加我从目录中的 xls 文件中提取的多个列集。每个 xls 文件的格式为:
Index Exp. m/z Intensity
1 1000.11 1000
2 2000.14 2000
3 3000.15 3000
每个文件都有不同数量的索引。下面是我的代码:
import pandas as pd
import os
import tkinter.filedialog
full_path = tkinter.filedialog.askdirectory(initialdir='.')
os.chdir(full_path)
data = {}
df = pd.DataFrame()
for files in os.listdir(full_path):
if os.path.isfile(os.path.join(full_path, files)):
df = pd.read_excel(files, 'Sheet1')[['Exp. m/z', 'Intensity']]
data = df.concat(df, axis=1)
data.to_excel('test.xls', index=False)
这会产生一个属性错误:DataFrame 对象没有属性 concat。我也试过使用 append like:
data = df.append(df, axis=1)
但我知道 append 没有 axis 关键字参数。 df.append(df) 确实有效,但它将列放在底部。我想要这样的东西:
Exp. m/z Intensity Exp. m/z Intensity
1000.11 1000 1001.43 1000
2000.14 2000 1011.45 2000
3000.15 3000
等等。所以我从每个文件中提取的列集应该放在前面的列集的右边,中间有一列space。
我想你需要 append
DataFrames
列出然后 pd.concat
:
dfs = []
for files in os.listdir(full_path):
if os.path.isfile(os.path.join(full_path, files)):
df = pd.read_excel(files, 'Sheet1')[['Exp. m/z', 'Intensity']]
#for add empty column
df['empty'] = np.nan
dfs.append(df)
data = pd.concat(dfs, axis=1)
我正在尝试制作一个简单的脚本,用于连接或附加我从目录中的 xls 文件中提取的多个列集。每个 xls 文件的格式为:
Index Exp. m/z Intensity
1 1000.11 1000
2 2000.14 2000
3 3000.15 3000
每个文件都有不同数量的索引。下面是我的代码:
import pandas as pd
import os
import tkinter.filedialog
full_path = tkinter.filedialog.askdirectory(initialdir='.')
os.chdir(full_path)
data = {}
df = pd.DataFrame()
for files in os.listdir(full_path):
if os.path.isfile(os.path.join(full_path, files)):
df = pd.read_excel(files, 'Sheet1')[['Exp. m/z', 'Intensity']]
data = df.concat(df, axis=1)
data.to_excel('test.xls', index=False)
这会产生一个属性错误:DataFrame 对象没有属性 concat。我也试过使用 append like:
data = df.append(df, axis=1)
但我知道 append 没有 axis 关键字参数。 df.append(df) 确实有效,但它将列放在底部。我想要这样的东西:
Exp. m/z Intensity Exp. m/z Intensity
1000.11 1000 1001.43 1000
2000.14 2000 1011.45 2000
3000.15 3000
等等。所以我从每个文件中提取的列集应该放在前面的列集的右边,中间有一列space。
我想你需要 append
DataFrames
列出然后 pd.concat
:
dfs = []
for files in os.listdir(full_path):
if os.path.isfile(os.path.join(full_path, files)):
df = pd.read_excel(files, 'Sheet1')[['Exp. m/z', 'Intensity']]
#for add empty column
df['empty'] = np.nan
dfs.append(df)
data = pd.concat(dfs, axis=1)