I have 2 columns in pandas like this:
column_a column_b
ok pen
ok book
0.615 C/H
0.551 I/H
Is there any way to concatenate these 2 columns into a column like this ?:
column_c
pen
book
0.615
0.551
I've tried so many ways but it can't give me the desired result i want,
There is a simple solution:
df = pd.DataFrame({"column_a": ["ok", "ok", 0.615, 0.551], "column_b": ["pen", "book", "C/H", "I/H"]})
# Generate your condition
CONDITION = df["column_a"] == "ok"
#Initilize your new column to the first one.
df.loc[:,"together"] = df["column_a"]
# Add new column with the condition, called together
df.loc[CONDITION, "together"] = df["column_b"]
column_a column_b together
0 ok pen pen
1 ok book book
2 0.615 C/H NaN
3 0.551 I/H NaN
So basically you create a copy of the first column and then you define a condition where you want to update the value. In this case I'm using column_a = "ok".
if you literally only need that, you can do it manually:
df
column_a column_b
0 ok pen
1 ok book
2 0.615 C/H
3 0.551 I/H
df['column_c'] = list(df.iloc[0:2, 1]) + list(df.iloc[2:,0])
df
column_a column_b column_c
0 ok pen pen
1 ok book book
2 0.615 C/H 0.615
3 0.551 I/H 0.551
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.