Reputation: 379
Sorry for the basic question but I can't seem to figure this out. I have the following dataframe:
df1
a
1 7
2 26
3 32
4 41
...
37 7
38 9
How would I go about repeating the value at the 37th index, twice such that the following is produced
df1
a
1 7
2 26
3 32
4 41
...
37 7
38 7
39 9
I've tried to use loc to no avail:
newp = df1[name].loc[np.repeat(df1.index[-2:].values, 1)] #get the 37th index value to repeat
listofwty[0].loc[36] = newp
listofwty[0].index = listofwty.index+1
Upvotes: 1
Views: 66
Reputation: 879191
You could use df.index.insert
to insert another entry of 37, and then use df.reindex
to duplicate the row:
import pandas as pd
df = pd.DataFrame({'a': [7, 26, 32, 41, 7, 9]}, index=[1, 2, 3, 4, 37, 38])
index = df.index
df = df.reindex(index.insert(index.get_loc(37), 37))
print(df)
yields
a
1 7
2 26
3 32
4 41
37 7
37 7
38 9
Note this create a DataFrame with a non-unique index. To make the index labels
unique, call df = df.reset_index(drop=True)
(as Scott Boston showed in his answer).
Upvotes: 3
Reputation: 153460
You could do it this way, using pd.concat
, then sort_index
:
pd.concat([df,df.loc[[37]]]).sort_index().reset_index(drop=True)
Output:
a
1 7
2 26
3 32
4 41
...
37 7
38 7
39 9
Upvotes: 2