pandas - add new column to dataframe from dictionary
Call map
and pass the dict, this will perform a lookup and return the associated value for that key:
In [248]:
d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'}
df['D'] = df['U'].map(d)
df
Out[248]:
U L D
0 111 en en
1 112 en en
2 112 es en
3 113 es es
4 113 ja es
5 113 zh es
6 114 es es
Add a new column to pandas data frame from dictionary
Construct the Series first:
df["industry"] = pd.Series(d)
Note: This assumes that the dict keys are in the DataFrame index:In [11]: df
Out[11]:
2015-12-01
KO 2144.499950
AAPL 5162.959824
In [12]: df["industry"] = pd.Series(d)
In [13]: df
Out[13]:
2015-12-01 industry
KO 2144.499950 Consumer, Non-cyclical
AAPL 5162.959824 Technology
How to add a column with values of a dictionary in Python
Is this what you want?
df = df.set_index('id')
dictionary = {1:[5,8,6,3], 2:[1,2], 5:[8,6,2]}
df['new_column'] = pd.Series(dictionary)
Note: The keys of the dictionary need to be the same type (int) as the index of the data frame.>>> print(df)
gender new_column
id
1 0 [5, 8, 6, 3]
2 0 [1, 2]
3 1 NaN
4 1 NaN
5 1 [8, 6, 2]
Update:A better solution if 'id'
column contains duplicates (see comments below):
df['new_column'] = df['id'].map(dictionary)
Pandas - Add Columns to a DataFrame Based in Dict from one of the Columns
You just need a slight change in your comprehension to extract that data.
It should be:
You want the values of the dictionary key 'rodada' to be the basis of your new column. So you iterate over those dictionary entries in the loop- in other words, d, and then extract the value by key to make the new column.df_times["rodada"] = [d.get('rodada') for d in
df_times["pontos"]]
map value of nested dictionary to new column in dataframe in python
Looks like a list comprehension with a double loop should do the job:
df['malicious'] = [d.get('malicious') for outer_d in df['dictionary'] for d in outer_d.values()]
or you can try the following code that creates a DataFrame out of the "dictionary" column and gets the value under the "malicious" key using str.get
:df['malicious'] = (pd.DataFrame(df['dictionary'].tolist()).set_axis([0]*len(df), axis=1)
.groupby(level=0, axis=1)
.first()[0]
.str.get('malicious'))
Output: dictionary malicious
0 {'https://twitter.com/tonythehuff/status/92718... False
1 {'http://giveaway.amazon.com\__CONNECTIONPOOL_... False
2 {'http://pcktpro.com\__CONNECTIONPOOL_ERROR__'... True
create a dataframe from a dictionary using the keys as a new column?
Use list comprehension for list of dictionaries with concat helper dict for FRUIT
column by keys of outer input dicts:
fruit_dict = {
"apple": [{
"price": 19,
"store": "xyz"
},
{
"price": 13,
"store": "abc"
}
],
"pear": [{
"price": 25,
"store": "xyz"
}]}
df = pd.DataFrame([{**{'FRUIT':k}, **x} for k, v in fruit_dict.items() for x in v])
print (df)
FRUIT price store
0 apple 19 xyz
1 apple 13 abc
2 pear 25 xyz
Related Topics
Convert Categorical Data in Pandas Dataframe
Python, Default Keyword Arguments After Variable Length Positional Arguments
Join Two Lists of Dictionaries on a Single Key
Numpy: Find Index of the Elements Within Range
How to Align Gridlines for Two Y-Axis Scales Using Matplotlib
Source Interface with Python and Urllib2
How to Change a Widget's Font Style Without Knowing the Widget's Font Family/Size
Preventing Python Code from Importing Certain Modules
Numpy Array Dtype Is Coming as Int32 by Default in a Windows 10 64 Bit MAChine
Python Decompression Relative Performance
Python [Errno 98] Address Already in Use
Find All Upper, Lower and Mixed Case Combinations of a String
How to Check Task Status in Celery
Disable Console Messages in Flask Server
How to Get Tweets Older Than a Week (Using Tweepy or Other Python Libraries)
Hide Chromedriver Console in Python
Global Dictionaries Don't Need Keyword Global to Modify Them
Multiprocessing.Pool Makes Numpy Matrix Multiplication Slower