Python 使用行分隔符转换数据帧
我创建了一个接受数据帧作为输入的函数:Python 使用行分隔符转换数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,我创建了一个接受数据帧作为输入的函数: a = {"string": ['xxx', 'yyy'], "array": [[1,2,3,4,5,6,1,2,3,6,6,2,2,3,5,6], [2,6,6]]} df = pd.DataFrame(a) string array 0 xxx [1, 2, 3, 4, 5, 6, 1, 2, 3, 6, 6, 2, 2, 3, 5, 6] 1 yyy [2, 6, 6] 并返回一个数据帧
a = {"string": ['xxx', 'yyy'], "array": [[1,2,3,4,5,6,1,2,3,6,6,2,2,3,5,6], [2,6,6]]}
df = pd.DataFrame(a)
string array
0 xxx [1, 2, 3, 4, 5, 6, 1, 2, 3, 6, 6, 2, 2, 3, 5, 6]
1 yyy [2, 6, 6]
并返回一个数据帧,其中某个分隔符编号(在本例中为6)是传递的参数:
string array
0 xxx [1, 2, 3, 4, 5, 6]
1 xxx [1, 2, 3, 6]
2 xxx [6]
3 xxx [2, 2, 3, 5, 6]
4 yyy [2, 6]
5 yyy [6]
以下是我得到的:
def df_conversion(df, sep=None):
data = {}
idx = []
for i in range(df.shape[0]):
key = df['string'].iloc[i]
value = df['array'].iloc[i]
spl = [[]]
for item in value:
if item == sep:
spl[-1].append(item)
idx.append(key)
spl.append([])
else:
spl[-1].append(item)
del spl[-1]
if i == 0: spl_0 = spl
if i == 1: spl_0.extend(spl)
data['string'] = idx
data['array'] = spl_0
return pd.DataFrame(data)
df_conversion(df, 6)
如何简化函数并使其更通用?
如何使功能更快?
谢谢。您可以使用和简洁地执行此操作:
sep=6
df.array=df.array.apply(λa:
np.split(a,1+np.where(np.array(a)==sep)[0][:-1]))
df=df.set_index('string')。explode('array')。reset_index()
#字符串数组
#0 xxx[1,2,3,4,5,6]
#xxx[1,2,3,6]
#2 xxx[6]
#3xxx[2,2,3,5,6]
#4 yyy[2,6]
#5 yyy[6]
解释和 我们用于查找
sep
的索引:
a=[1,2,3,4,5,6,1,2,3,6,6,2,2,3,5,6]
九月=6
其中(np.数组(a)=sep)[0]
#数组([5,9,10,15])
但是,在每个索引之后进行拆分,将sep
放在每个拆分的开头:
np.split(a,np.where(np.array(a)=sep)[0])
#[数组([1,2,3,4,5]),
#数组([6,1,2,3]),
#数组([6]),
#数组([6,2,2,3,5]),
#数组([6])]
相反,OP希望在每个索引之前进行拆分,以在每个拆分结束时保留sep
,因此我们移动拆分索引(1+
),并删除不再存在的最后一个拆分索引([:-1]
):
np.split(a,1+np.where(np.array(a)==sep)[0][:-1])
#[数组([1,2,3,4,5,6]),
#数组([1,2,3,6]),
#数组([6]),
#数组([2,2,3,5,6])]
与以下部件一起使用:
+1但是你介意解释一下
1+
和[:-1]
以节省理解的时间吗?我认为,在你离开他们,看看你得到了什么之前,乍一看(至少对我来说)还不清楚。
In [2174]: sep = '6'
In [2167]: df.array = df.array.apply(lambda x: ','.join(map(str, x))).str.split(sep)
In [2168]: df = df.explode('array')
In [2169]: df.array = df.array + sep
In [2171]: df.array = np.where(df.array.str.startswith(','), df.array.str[1:], df.array)
In [2183]: df = df.drop_duplicates()
In [2172]: df.array = df.array.str.split(',')
In [2186]: df
Out[2186]:
string array
0 xxx [1, 2, 3, 4, 5, 6]
0 xxx [1, 2, 3, 6]
0 xxx [6]
0 xxx [2, 2, 3, 5, 6]
1 yyy [2, 6]
1 yyy [6]