I have a dataframe with some reference values:
ref_value = {A:111, B:222, C:333, D:444}
df = pd.DataFrame(ref_value)
|foo|bar|
|---|---|
|A  |111|
|B  |222|
|C  |333|
|D  |444|
I then want to use it to create a bigger dataset to look like this:
| x | y |
|---|---|
|1  |111|
|2  |111|
|3  |111|
|4  |111|
|5  |111|
|6  |222|
|7  |222|
|8  |222|
|9  |222|
|10 |222|
|11 |333|
|12 |333|
|13 |333|
|14 |333|
|15 |333|
|16 |444|
|17 |444|
|18 |444|
|19 |444|
|20 |444|
This is how I've done it:
new_df = pd.DataFrame(np.arange(20))
new_df.loc[new_df.x <= 5, 'y'] = df.loc[df.foo == 'A', 'bar'].iloc[0]
new_df.loc[(new_df.x > 5) & (new_df.x <= 10), 'y'] = df.loc[df.foo == 'B', 'bar'].iloc[0]
new_df.loc[(new_df.x > 10) & (new_df.x <= 15), 'y'] = df.loc[df.foo == 'C', 'bar'].iloc[0]
new_df.loc[new_df.x > 15, 'y'] = df.loc[df.foo == 'D', 'bar'].iloc[0]
May I have some suggestions on how to do this more easily/elegantly?
I can't seem to get df.apply(lambda x: function) to work in this case.
NB: The actual DataFrames I'm working with are a bit larger.
Thanks in advance.
 
     
     
    