Issue
I have a df that looks like this:
col1
aaa
1
bbb
2
ccc
3
How do I pull at every second row out of the dataframe and make it, its own column like so:
col1 col2
aaa 1
bbb 2
ccc 3
I tried this:
df[::1]
since the second row has an index of 1, but I am not returned the data I am looking for.
Solution
Using reshape
pd.DataFrame(df.col1.values.reshape(-1,2),columns=['c1','c2'])
Full example:
import pandas as pd
df = pd.DataFrame({
'col1': ['aaa','1','bbb','2','ccc','3']
})
df = pd.DataFrame(df.col1.values.reshape(-1,2),columns=['c1','c2'])
df.c2 = df.c2.astype(int) # optional to convert col to int
print(df)
Returns
c1 c2
0 aaa 1
1 bbb 2
2 ccc 3
Answered By - BENY
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.