mea*_*ory 4 python dataframe pandas
Stata具有函数expand,它将行添加到与特定列中的值对应的数据库中.例如:
我有:
df = pd.DataFrame({"A":[1, 2, 3],
"B":[3,4,5]})
A B
0 1 3
1 2 4
2 3 5
Run Code Online (Sandbox Code Playgroud)
我需要的:
df2 = pd.DataFrame({"A":[1, 2, 3, 2, 3, 3],
"B":[3,4,5, 4, 5, 5]})
A B
0 1 3
1 2 4
2 3 5
3 2 4
4 3 5
6 3 5
Run Code Online (Sandbox Code Playgroud)
df.loc [0,'A']中的值为1,因此没有额外的行添加到DataFrame的末尾,因为B = 3只应该发生一次.
df.loc [1,'A']中的值为2,因此在DataFrame的末尾添加了一个观察值,使B = 4的总出现次数为2.
df.loc [2,'A']中的值为3,因此将两个观察值添加到DataFrame的末尾,使得B = 5的总出现次数为3.
为了让我开始,我已经仔细研究了以前的问题,但没有运气.任何帮助表示赞赏.
有许多可能性,都是围绕着np.repeat:
def using_reindex(df):
return df.reindex(np.repeat(df.index, df['A'])).reset_index(drop=True)
def using_dictcomp(df):
return pd.DataFrame({col:np.repeat(df[col].values, df['A'], axis=0)
for col in df})
def using_df_values(df):
return pd.DataFrame(np.repeat(df.values, df['A'], axis=0), columns=df.columns)
def using_loc(df):
return df.loc[np.repeat(df.index.values, df['A'])].reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)
例如,
In [219]: df = pd.DataFrame({"A":[1, 2, 3], "B":[3,4,5]})
In [220]: df.reindex(np.repeat(df.index, df['A'])).reset_index(drop=True)
Out[220]:
A B
0 1 3
1 2 4
2 2 4
3 3 5
4 3 5
5 3 5
Run Code Online (Sandbox Code Playgroud)
这是1000行DataFrame的基准测试; 结果是一个大约500K行的DataFrame:
In [208]: df = make_dataframe(1000)
In [210]: %timeit using_dictcomp(df)
10 loops, best of 3: 23.6 ms per loop
In [218]: %timeit using_reindex(df)
10 loops, best of 3: 35.8 ms per loop
In [211]: %timeit using_df_values(df)
10 loops, best of 3: 31.3 ms per loop
In [212]: %timeit using_loc(df)
1 loop, best of 3: 275 ms per loop
Run Code Online (Sandbox Code Playgroud)
这是我用来生成的代码df:
import numpy as np
import pandas as pd
def make_dataframe(nrows=100):
df = pd.DataFrame(
{'A': np.arange(nrows),
'float': np.random.randn(nrows),
'str': np.random.choice('Lorem ipsum dolor sit'.split(), size=nrows),
'datetime64': pd.date_range('20000101', periods=nrows)},
index=pd.date_range('20000101', periods=nrows))
return df
df = make_dataframe(1000)
Run Code Online (Sandbox Code Playgroud)
如果只有几列,using_dictcomp则最快.但请注意,using_dictcomp假设df具有唯一的列名称.字典理解using_dictcomp不会重复重复的列名.但是,其他替代方法将使用重复的列名称.
both using_reindex和using_locassume df都有一个唯一的索引.
using_reindex来自cᴏʟᴅsᴘᴇᴇᴅ的using_loc,在一个(不幸的)现在删除的帖子.cᴏʟᴅsᴘᴇᴇᴅ表示没有必要手动重复所有值 - 您只需重复索引然后让df.loc(或df.reindex)为您重复所有行.它还避免了访问df.values,object如果df包含多个dtypes的列,则可以生成dtype 的中间NumPy数组.
| 归档时间: |
|
| 查看次数: |
838 次 |
| 最近记录: |