假设我有一个这样的DatFrame:
col1 | col2 |
---|---|
1 | 3 |
2 | 4 |
我想对它应用一个函数,以便复制每一行并添加一个新列.对于为偶数值COL1创建的重复行,新列中的值是‘a’和‘b’,对于奇数值COL1,新列中的值是‘c’和‘d’.
因此,所需的输出为:
col1 | col2 | col3 |
---|---|---|
1 | 3 | c |
1 | 3 | d |
2 | 4 | a |
2 | 4 | b |
我试图通过迭代所有行来简单地解决这个问题,并得到了我想要的结果,
但据我所知,如果我们有数十万行,iterrows()
行是非常慢的.
import pandas as pd
import numpy as np
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
def add_rows(row):
"""
This function is used in apply function. It adds a new column and adds rows to the dataframe.
:param row:
:return:
"""
col3 = np.array(['a', 'b'])
out_df = pd.DataFrame([row.tolist()], columns=row.index)
out_df['col3'] = None
if row['col1'] % 2 == 0:
out_df.at[0, 'col3'] = col3
else:
out_df.at[0, 'col3'] = np.array(['c', 'd'])
out = out_df.explode('col3', ignore_index=True)
return out
cols = list(df.columns)
cols.append('col3')
result = pd.DataFrame(columns=cols)
for index, row in df.iterrows():
rows = add_rows(row)
result = pd.concat([result, rows])
result.reset_index(drop=True, inplace=True)
print(result)
我的数据有几十万行和几千列.
这能以更好的方式实现吗?
我曾try 对此函数执行apply
次,但得到了一些奇怪的输出.
也许Apply需要返回一些不同于数据框的内容才能正常工作?