如何在Python(含Pandas)中合并两个向量?
嘿,我来帮你梳理下在Python(包括Pandas)里怎么实现类似R中合并向量的操作~
一、基础Python中的列表合并(对应R的向量)
Python里没有直接叫"向量"的结构,最接近的就是列表(list),合并起来非常直观,有几种常用方式:
1. 合并两个列表
用+运算符就能直接拼接,和R里的c()用法逻辑很像:
list_1 = ["a", "b", "c"] list_2 = ["d", "e", "f"] # 拼接两个列表,返回新列表 combined_list = list_1 + list_2 print(combined_list) # 输出: ['a', 'b', 'c', 'd', 'e', 'f']
2. 列表与单个元素合并
如果要把单个元素加到列表里,只需要把元素放进一个临时列表再用+,或者用append()方法(注意append是直接修改原列表,而+是返回新列表):
list_1 = ["a", "b", "c"] single_item = "g" # 方式1:返回新列表 combined_with_single = list_1 + [single_item] print(combined_with_single) # 输出: ['a', 'b', 'c', 'g'] # 方式2:修改原列表 list_1.append(single_item) print(list_1) # 输出: ['a', 'b', 'c', 'g']
二、Pandas中的Series合并(对应R的向量)
如果用Pandas处理数据,Series就是对应R向量的结构,合并推荐用pd.concat()(旧版的append()方法已经被标记为弃用,不建议再用):
1. 合并两个Series
import pandas as pd s1 = pd.Series(["a", "b", "c"]) s2 = pd.Series(["d", "e", "f"]) # 拼接两个Series,ignore_index=True用来重置索引,避免索引重复 combined_series = pd.concat([s1, s2], ignore_index=True) print(combined_series) # 输出: # 0 a # 1 b # 2 c # 3 d # 4 e # 5 f # dtype: object
2. Series与单个元素合并
同样可以用pd.concat(),把单个元素包装成Series再拼接:
s1 = pd.Series(["a", "b", "c"]) single_elem = pd.Series(["g"]) combined_with_single = pd.concat([s1, single_elem], ignore_index=True) print(combined_with_single) # 输出: # 0 a # 1 b # 2 c # 3 g # dtype: object
内容的提问来源于stack exchange,提问作者stevec
相关产品推荐
相关产品推荐

