Add columns in pandas dataframe dynamically

2024/10/8 8:30:55

I have following code to load dataframe

import pandas as pdufo = pd.read_csv('csv_path')
print(ufo.loc[[0,1,2] , :])

which gives following output, see the structure of the csv

          City Colors Reported Shape Reported State             Time
0       Ithaca             NaN       TRIANGLE    NY   6/1/1930 22:00
1  Willingboro             NaN          OTHER    NJ  6/30/1930 20:00
2      Holyoke             NaN           OVAL    CO  2/15/1931 14:00

Now, I want to add an extra column based on existing column. I have a list which consist of indices of participating columns. It can be 0,1 or 0,2,3 or 1,2,3 anything.

I need to create it dynamically. I could come up with following

df1['combined'] = df1['City']+','+df1['State']

Putting index doesn't seem to work. I want to join those columns. using ','.join()

Answer

Assuming the data types of all the columns you want to join are str, you can use [] with integer to pick up the columns and use apply to join them:

df[[0,2,3]].apply(','.join, axis=1)#0      Ithaca,TRIANGLE,NY
#1    Willingboro,OTHER,NJ
#2         Holyoke,OVAL,CO
#dtype: object
https://en.xdnf.cn/q/70139.html

Related Q&A

How do you add input from user into list in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

How to suppress matplotlib inline for a single cell in Jupyter Notebooks/Lab?

I was looking at matplotlib python inline on/off and this kind of solves the problem but when I do plt.ion() all of the Figures pop up (100s of figures). I want to keep them suppressed in a single cel…

Using django-filer, can I chose the folder that images go into, from Unsorted Uploads

Im using django-filer for the first time, and it looks great, and work pretty well.But all my images are being uploaded to the Unsorted Uploads folder, and I cant figure out a way to put them in a spec…

how to use distutils to create executable .zip file?

Python 2.6 and beyond has the ability to directly execute a .zip file if the zip file contains a __main__.py file at the top of the zip archive. Im wanting to leverage this feature to provide preview r…

Pass nested dictionary location as parameter in Python

If I have a nested dictionary I can get a key by indexing like so: >>> d = {a:{b:c}} >>> d[a][b] cAm I able to pass that indexing as a function parameter? def get_nested_value(d, pat…

Correct way to deprecate parameter alias in click

I want to deprecate a parameter alias in click (say, switch from underscores to dashes). For a while, I want both formulations to be valid, but throw a FutureWarning when the parameter is invoked with …

How to rename a file with non-ASCII character encoding to ASCII

I have the file name, "abc枚.xlsx", containing some kind of non-ASCII character encoding and Id like to remove all non-ASCII characters to rename it to "abc.xlsx".Here is what Ive t…

draw random element in numpy

I have an array of element probabilities, lets say [0.1, 0.2, 0.5, 0.2]. The array sums up to 1.0.Using plain Python or numpy, I want to draw elements proportional to their probability: the first eleme…

Python Gevent Pywsgi server with ssl

Im trying to use gevent.pywsgi.WSGIServer to wrap a Flask app. Everything works fine, however, when I try to add a key and a certificate for ssl, its not even able to accept any clients anymore.This is…

unexpected keyword argument buffering - python client

I am receiving the error as "getresponse() got an unexpected keyword argument buffering". Complete error log is :[INFO ] Kivy v1.8.0 [INFO ] [Logger ] Record lo…