Which method should i use to concate two dataframes in Pandas like:
before: dataframes1 =[1,2,3,4,5,6] dataframes2 =['a','b','c','d','e','f']
after: ['1a','2b','3c','4d','5e','6f']
Which method should i use to concate two dataframes in Pandas like:
before: dataframes1 =[1,2,3,4,5,6] dataframes2 =['a','b','c','d','e','f']
after: ['1a','2b','3c','4d','5e','6f']
You can use a for
loop to traverse both lists and concatenate the results in a new list:
dataframes1 =[1,2,3,4,5,6]
dataframes2 =['a','b','c','d','e','f']
result = []
for i in range(len(dataframes1)):
result.append(str(dataframes1[i])+dataframes2[i])
print(result)
- Also you can simplify the syntax of the loop by invoking it in the list initialization:
dataframes1 =[1,2,3,4,5,6]
dataframes2 =['a','b','c','d','e','f']
result = [str(dataframes1[i])+dataframes2[i] for i in range(len(dataframes1))]
print(result)
- Or use the zip()
function to make the syntax clearer, as @patrick-artner suggested:
dataframes1 =[1,2,3,4,5,6]
dataframes2 =['a','b','c','d','e','f']
result = [str(a)+b for a,b in zip(dataframes1, dataframes2)]
print(result)
Output:
['1a', '2b', '3c', '4d', '5e', '6f']
If it is pandas dataframe and both columns are strings, you can concatenate them;
import pandas as pd
# create empty dataframe
dataframes3 = pd.DataFrame()
# Concatenation of two columns
dataframes3["result"] = dataframes1["column1"] + dataframes2["column1"]
If it is Python List.
result = map(lambda (s1,s2): s1+s2, zip(dataframes1, dataframes2))