[Python Data Frame] When the value is empty, fill it with the value of another column.

Assumed data

The following demographic data.

I want to put the prefecture name where the city name is NaN.

Group code Prefecture name Municipality name Gender Total number 0-4 years old 5-9 10-14 15-19\
3      10006.0 Hokkaido*NaN total 5339539 181591 201119 213206 231870
4      10006.0 Hokkaido*NaN Man 2522526 93048 102850 108783 118414
5      10006.0 Hokkaido*NaN Woman 2817013 88543 98269 104423 113456
6      11002.0 Sapporo, Hokkaido Total 1952348 71281 75025 76342 82644
7      11002.0 Sapporo, Hokkaido Man 913077 36715 38250 38839 41729

code


df['City name'].fillna(df['Name of prefectures'], inplace=True)

#It's possible here, but it seems to be slower.
df.loc[pd.isnull(df['City name']), ['City name']] = df['Name of prefectures']

Failed code


for i, (prefecture, city) in enumerate(zip(df['Name of prefectures'], df['City name'])):
    if pd.isnull(city):
        df['City name'][i] = prefecture

result


<ipython-input-59-8ff91f161741>:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['City name'][i] = prefecture
​

reference

Recommended Posts

[Python Data Frame] When the value is empty, fill it with the value of another column.
Extract the band information of raster data with python
[Solution] When inserting "0001" into the column of string in sqlite3, it is entered as "1".
The timing when the value of the default argument is evaluated is different between Ruby and Python.
Try scraping the data of COVID-19 in Tokyo with Python
The story of rubyist struggling with python :: Dict data with pycall
[Homology] Count the number of holes in data with Python
Return the image data with Flask of Python and draw it to the canvas element of HTML
In the python dictionary, if a non-existent key is accessed, initialize it with an arbitrary value
March 14th is Pi Day. The story of calculating pi with python
Tips: [Python] Calculate the average value of the specified area with bedgraph
I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python
Memorandum of understanding when Python is run on EC2 with Apache
What to do when the value type is ambiguous in Python?
A simple reason why the return value of round (2.675,2) is 2.67 in python (it should be 2.68 in reality ...)
I'm tired of Python, so I analyzed the data with nehan (corona related, is that word now?)
The story of making a tool to load an image with Python ⇒ save it as another name
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
Try to image the elevation data of the Geographical Survey Institute with Python
Plot CSV of time series data with unixtime value in Python (matplotlib)
Find out the name of the method that called it from the method that is python
Get the return value of an external shell script (ls) with python3
[Introduction to Python] What is the method of repeating with the continue statement?
Get the column list & data list of CASTable
Check the existence of the file with python
[python] [meta] Is the type of python a type?
Recommendation of Altair! Data visualization with Python
It seems that the version of pyflakes is not the latest when flake8 is installed
[Python] Precautions when retrieving data by scraping and putting it in the list
Fill the missing value (null) of DataFrame with the values before and after with pyspark
In Python, change the behavior of the method depending on how it is called
When using PyQtGraph with Python Pyside, pay attention to the order of import
"Brute force of MD5 hash value of 6-digit password" I tried it with Python
Compare the sum of each element in two lists with the specified value in Python
Notify slack when the switch sales page is updated ~ slack bot development with python ③ ~
Align the number of samples between classes of data for machine learning with Python
[Introduction to Python] How to get the index of data with a for statement
Try to find the probability that it is a multiple of 3 and not a multiple of 5 when one is removed from a card with natural numbers 1 to 100 using Ruby and Python.
Prepare the execution environment of Python3 with Docker
2016 The University of Tokyo Mathematics Solved with Python
Find the mood value with python (Rike Koi)
[Note] Export the html of the site with python.
The answer of "1/2" is different between python2 and 3
Calculate the total number of combinations with python
Deep Learning! The story of the data itself that is read when it does not follow after handwritten number recognition
Check the date of the flag duty with Python
The value of pyTorch torch.var () is not distributed
Find the divisor of the value entered in python
This is the only basic review of Python ~ 1 ~
This is the only basic review of Python ~ 2 ~
Fill the browser with the width of Jupyter Notebook
The story of reading HSPICE data in Python
This is the only basic review of Python ~ 3 ~
Convert the character code of the file with Python3
[Python] Determine the type of iris with SVM
Predicting the goal time of a full marathon with machine learning-③: Visualizing data with Python-
Investigate the cause when an error is thrown when python3.8 is not found when using lambda-uploader with python3.8
Get the value of a specific key in a list from the dictionary type in the list with Python
[Shell art] Only when it is a multiple of 3 and a number with 3 becomes stupid
When reading a csv file with read_csv of pandas, the first column becomes index
How to check in Python if one of the elements of a list is in another list