我正在将一个序列连接到一个数据帧上,但是列名(Series name)没有显示在新的数据帧上。在
相反,该列在最终数据帧中的名称为“0”,但在apply\u join方法中生成时,该名称确实显示出来。在
为什么在数据帧中看不到序列名?在
import pandas as pd
from io import StringIO
tibble3_csv = """country,year,cases,population
Afghanistan,1999,745,19987071
Afghanistan,2000,2666,20595360"""
with StringIO(tibble3_csv) as fp:
tibble3 = pd.read_csv(fp)
def str_join_elements(x, sep=""):
assert type(sep) is str
return sep.join((str(xi) for xi in x))
def unite(df, cols, new_var, combine=str_join_elements):
def apply_join(x, combine):
joinstr = combine(x)
ser = pd.Series(joinstr, name=new_var)
print(ser.name)
return ser
fixed_vars = df.columns.difference(cols)
tibble = df[fixed_vars].copy()
tibble_extra = df[cols].apply(apply_join, combine=combine, axis=1)
return pd.concat([tibble, tibble_extra], axis=1)
tab = unite(tibble3, ['cases', 'population'], 'rate', combine=lambda x: str_join_elements(x, "/"))
print(tab)
结果:
^{pr2}$
您也可以尝试使用
如果您试图连接未知数量的列,可以将
apply
与str.join
一起使用:如果总是两列,那么可以使用
^{pr2}$str.cat
,这样会更快。在相关问题 更多 >
编程相关推荐