'Populating values not explicitly stated in dataframe
How can I add missing column values to a dataframe based off list of possible values.
the list of values looks like:
type = ['type1','type2','type3','type4']
Here's code for df:
import pandas as pd
data = {
'1': ['fall', 'type2', 'MATH 1234', 'Yes'],
'2': ['fall', 'type1', 'MATH 1234', 'Yes']
}
columns=['term', 'type', 'course', 'offered']
df = pd.DataFrame.from_dict(
data=data, orient='index'
)
df.columns = columns
dataframe looks like:
term type course offered
1 fall type2 MATH 1234 Yes
2 fall type1 MATH 1234 Yes
desired output:
term type course offered
1 fall type2 MATH 1234 Yes
2 fall type1 MATH 1234 Yes
3 fall type3 MATH 1234 NO
4 fall type4 MATH 1234 NO
type3 and type4 are not offered for MATH 1234 in the fall therefore offered should be "NO".
Any ideas how to handle this?
Solution 1:[1]
The goal here is to get the missing rows for the combination of (term, course)
with the new values for type
. One option is with complete from pyjanitor to expose the missing rows:
# pip install pyjanitor
import pandas as pd
import janitor
df.complete(['term', 'course'], {'type': type}, fill_value = 'NO')
term type course offered
0 fall type1 MATH 1234 Yes
1 fall type2 MATH 1234 Yes
2 fall type3 MATH 1234 NO
3 fall type4 MATH 1234 NO
complete takes a variable number of arguments - the dictionary allows us to pass in the new values for type
.
Solution 2:[2]
If you're using .NET 6, you could directly use JsonArray
from System.Text.Json.Nodes. For instance, to get first unknown key
:
using System.Text.Json;
using System.Text.Json.Nodes;
var json_string = @"
[
{
""id"":""100"",
""name"": ""myname"",
""playlists"": {
""unknown key"": [""song 1"", ""song2""]
}
}
]
";
var guild = JsonSerializer.SerializeToNode(JsonNode.Parse(json_string)) as JsonArray;
var firstUnknownKey = guild[0]["playlists"]["unknown key"][0];
WriteLine(firstUnknownKey); // Prints: song 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sammywemmy |
Solution 2 | JohnyL |