concat+
我想让这段代码更加优雅和简洁。我有三个数据帧需要组合使用Seaborn色调。我需要为色调本身添加一个关键点。
这就是我所想到的,但我觉得必须有一种更优雅、更高效的方法
df = pd.DataFrame({ 'A' : range(3), 'B' : range(3) })
frames = (df.copy(), df.copy(), df.copy())
f_names = ["one", "two", "three"]
dff = pd.DataFrame()
for e, f in enumerate(frames):
tmp = f.copy()
tmp['name'] = f_names[e]
dff = dff.append(tmp, ignore_index=True)
print(dff)
Output:
A B name
0 0 0 one
1 1 1 one
2 2 2 one
3 0 0 two
4 1 1 two
5 2 2 two
6 0 0 three
7 1 1 three
8 2 2 three
谢谢!
IIUC,您需要重复n次df
并添加n个标签(此处n=3(。
你有几个选择。
concat+np.repeat
将输入连接n次,并将重复的标签添加为新列。
f_names = ["one", "two", "three"]
dff = pd.concat([df]*len(f_names), ignore_index=True)
dff['C'] = np.repeat(f_names, len(f_names))
如果您有不同的数据帧,此选项也适用:
dfs = [df1, df2, df3]
f_names = ["one", "two", "three"]
dff = pd.concat(dfs, ignore_index=True)
dff['C'] = np.repeat(f_names, list(map(len, dfs)))
或者使用字典作为输入:
dff = (pd.concat({'one': df1, 'two': df2, 'three': df3}, names='C')
.reset_index(level=0)
)
交叉合并
您可以使用精心制作的系列执行交叉merge
。
s = pd.Series(['one', 'two', 'three'], name='C')
dff = df.merge(s, how='cross')
输出:
A B C
0 0 0 one
1 0 0 two
2 0 0 three
3 1 1 one
4 1 1 two
5 1 1 three
6 2 2 one
7 2 2 two
8 2 2 three
如果行的顺序真的很重要,那么您可以将此选项与pandas.merge
(系列第一(一起使用:
s = pd.Series(['one', 'two', 'three'], name='C')
dff = pd.merge(s, df, how='cross')[list(df.columns)+[s.name]]
输出:
A B C
0 0 0 one
1 1 1 one
2 2 2 one
3 0 0 two
4 1 1 two
5 2 2 two
6 0 0 three
7 1 1 three
8 2 2 three