Issue
I am trying to port code from R to python, part of which converts and object to different object using data <- tidyr::unnest(data)
.
I have tried different ways like pd.json_normalize(df, sep=' '), pd.DataFrame(A).explode('id')
but not getting desired output.
Input object:
{
"id": [
"3",
"3",
"3",
],
"a": [
"1",
"1",
"1",
],
"b": [
"1",
"2",
"3",
],
"c": [
"1",
"1",
"1",
],
"d": [
"1",
"1",
"1",
],
"e": [
0,
0,
0,
]
}
desired output object:
"id" "a" "b" "c" "d" "e"
"3" "1" "1" "1" "1" 0
"3" "1" "2" "1" "1" 0
"3" "1" "3" "1" "1" 0
"3" "1" "4" "1" "1" 0
"3" "1" "5" "1" "1" 0
Thanks,
Solution
Your data doesn't line up with your output but essentially you want:
pd.DataFrame.from_dict(d, orient = "index").transpose()
id a b c d e
0 3 1 1 1 1 0
1 3 1 2 1 1 0
2 3 1 3 1 1 0
If you must have this exact output from your input you can do:
df = (
pd.DataFrame
.from_dict(d, orient = "index")
.transpose()
.reindex((range(5)))
.apply(pd.to_numeric)
)
cols = list(set(df.columns).difference("b"))
df[cols] = df[cols].ffill()
df.interpolate('slinear', fill_value='extrapolate', limit_direction='both', axis=0)
id a b c d e
0 3.0 1.0 1.0 1.0 1.0 0.0
1 3.0 1.0 2.0 1.0 1.0 0.0
2 3.0 1.0 3.0 1.0 1.0 0.0
3 3.0 1.0 4.0 1.0 1.0 0.0
4 3.0 1.0 5.0 1.0 1.0 0.0
Answered By - SamR
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.