我在熊猫中有2列,像这样:
column_a column_b
ok pen
ok book
0.615 C/H
0.551 I/H
是否可以将这2列连接成这样的列?:
column_c
pen
book
0.615
0.551
我已经尝试了很多方法,但是不能给我想要的结果,
答案 0 :(得分:1)
有一个简单的解决方案:
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
因此,基本上,您创建第一列的副本,然后定义要更新值的条件。在这种情况下,我使用column_a =“ ok”。
答案 1 :(得分:0)
如果您只需要它,可以手动进行:
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