到目前为止,我的努力微乎其微。事实上,我不知道用熊猫来接近它。
我得到了一个偶数和奇数的列表,我需要拆分这个列表,并将它粘贴到相邻的列中,并对列表执行一个串联命令。
for example my list reads:
odd even
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20 因此,我使用excel串联命令将列拆分为两部分,并将其连接起来。
Expected result:
odd-odd even-even
111 212
313 414
515 616
717 818
919 1020帮助!
最低工作代码:
import pandas as pd
list2=[1,3,5,7,9,11,13,15,17,19]
df = pd.DataFrame((list2), columns=['odd'])
df = df.astype(str).groupby(df['odd'].astype(str).str[-1]).agg({"odd": lambda x: "".join(x)}).reset_index(drop=True)
print (df)产出:
odd
0 111
1 313
2 515
3 717
4 919但是当我将更多的值添加到列表示例中时: list2=1,3,5,7,9,11,13,15,17,19,21,23,25,27
odd
0 11121
1 31323
2 51525
3 71727
4 919我要找的是:
115
317
519
721
923
1125
1327这样就行了。感谢大家的努力。
import pandas as pd
list2=[1,3,5,7,9,11,13,15,17,19,21,23,25,27]
df = pd.DataFrame((list2), columns=['odd'])
n2 = len(df)
n1 = int(n2/2)
df2 = pd.DataFrame()
df2['odd-odd'] = df.odd[0:n1].astype(str).to_numpy()+df.odd[n1:n2].astype(str).to_numpy()
print (df2['odd-odd'])发布于 2020-06-27 05:35:36
可以使用.to_numpy()组合列。这样,你就不用担心不匹配的指数了。
df2 = pd.DataFrame()
df2['odd-odd']=df.odd[0:5].astype(str).to_numpy()+df.odd[5:10].astype(str).to_numpy()
df2['even-even']=df.even[0:5].astype(str).to_numpy()+df.even[5:10].astype(str).to_numpy()
print(df2)输出:
odd-odd even-even
0 111 212
1 313 414
2 515 616
3 717 818
4 919 1020以df长度作为变量进行更新:
n2 = len(df)
n1 = int(n2/2)
df2 = pd.DataFrame()
df2['odd-odd']=df.odd[0:n1].astype(str).to_numpy()+df.odd[n1:n2].astype(str).to_numpy()
df2['even-even']=df.even[0:n1].astype(str).to_numpy()+df.even[n1:n2].astype(str).to_numpy()发布于 2020-06-27 04:59:24
尝试此操作,将所有列转换为string提取的最后一个元素作为groupby的参考,应用aggregate & join。
(
df.astype(str).
groupby(df['odd'].astype(str).str[-1]).
agg({"odd": lambda x: "".join(x), "even": lambda x: "".join(x)}).
reset_index(drop=True)
) odd even
0 111 212
1 313 414
2 515 616
3 717 818
4 919 1020发布于 2020-06-27 05:29:43
下面是一种使用numpy数据转换的方法:
# apply function along axis
flag = np.apply_along_axis(lambda x: x <= 10, 1, df.values)
print(flag)
[[ True True]
[ True True]
[ True True]
[ True True]
[ True True]
[False False]
[False False]
[False False]
[False False]
[False False]]
# split the True/False in separate arrays
v1 = df.values[flag].reshape(-1, 2)
v2 = df.values[~flag].reshape(-1, 2)
print(v1)
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10]])
print(v2)
array([[11, 12],
[13, 14],
[15, 16],
[17, 18],
[19, 20]])
# simply join the data and paste the columns
v3 = np.hstack([v1, v2])
v1 = np.apply_along_axis(lambda x: str(x[0])+str(x[2]), 1, v3)
v2 = np.apply_along_axis(lambda x: str(x[1])+str(x[3]), 1, v3)
df = pd.DataFrame({'odd-odd': v1, 'even-even': v2})
print(df)
odd-odd even-even
0 111 212
1 313 414
2 515 616
3 717 818
4 919 102https://stackoverflow.com/questions/62605935
复制相似问题