I am trying to duplicate a column multiple time from a df such as
df.head()
close
date
2015-09-23 17:00:00 1.3324
2015-09-23 17:01:00 1.3325
2015-09-23 17:02:00 1.3323
2015-09-23 17:03:00 1.3323
2015-09-23 17:04:00 1.3323
from a certain list of name, I want to duplicate that colum as many time as there is name in my list:
list =['a','b','c']
and get
df.head()
close a b c
date
2015-09-23 17:00:00 1.3324 1.3324 1.3324 1.3324
2015-09-23 17:01:00 1.3325 1.3325 1.3325 1.3325
2015-09-23 17:02:00 1.3323 1.3323 1.3323 1.3323
2015-09-23 17:03:00 1.3323 1.3323 1.3323 1.3323
2015-09-23 17:04:00 1.3323 1.3323 1.3323 1.3323
I tried
df[list] = df
but columns must be same length as key. Thanks for your help!
We can use str. split() to split one column to multiple columns by specifying expand=True option.
Return Multiple Columns from pandas apply() You can return a Series from the apply() function that contains the new data. pass axis=1 to the apply() function which applies the function multiply to each row of the DataFrame, Returns a series of multiple columns from pandas apply() function.
split() function is used to break up single column values into multiple columns based on a specified separator or delimiter. The Series. str. split() function is similar to the Python string split() method, but split() method works on the all Dataframe columns, whereas the Series.
Combine Two Columns Using + OperatorBy use + operator simply you can combine/merge two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.
The simplest way would be to iterate through your list and create a new column for each key (side note: you should probably avoid using list
as the name of a variable, since you'll overwrite the native list
):
keys = ['a','b','c']
for k in keys:
df[k] = df['close']
If you want to do it in one line, without a loop, you could do the following:
keys = ['a','b','c']
df = df.join(pd.concat([df.close]*len(keys), keys=keys))
Moving outwards from the middle, [df.close]*len(keys)
creates a list with as many copies of the original dataframe column as there are keys in your list. These are then combined into one dataframe using pd.concat()
, with the column names being set with your list (keys=keys
). Now that you have a dataframe with your duplicate columns, you can add it to the original dataframe using df.join()
.
You can use concat
:
li = ['a','b','c']
df1 = pd.concat([df['close']]*(len(li)+1), axis=1, keys=['close'] + li)
print (df1)
close a b c
date
2015-09-23 17:00:00 1.3324 1.3324 1.3324 1.3324
2015-09-23 17:01:00 1.3325 1.3325 1.3325 1.3325
2015-09-23 17:02:00 1.3323 1.3323 1.3323 1.3323
2015-09-23 17:03:00 1.3323 1.3323 1.3323 1.3323
2015-09-23 17:04:00 1.3323 1.3323 1.3323 1.3323
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With