如何将单个用户ID的多行写入数据帧

时间:2018-08-09 12:34:00

标签: python pandas dataframe

如何将多个行写入单个用户ID

示例

tags=None

预期输出:数据框

id = ['userid1','userid2'....'useridn']
ndarry1 = [1,2,3,4,5...]
ndarry2 = [1,2,3,4,5...]
.
.
ndarryn = [1,2,3,4,5...]

有人可以建议我该怎么做吗??

2 个答案:

答案 0 :(得分:0)

id = ['userid1', 'userid2', 'userid3', 'userid4']
ndarray1 = [1, 2, 3, 4]
ndarray2 = [1, 2, 3, 4]
ndarray3 = [1, 2, 3, 4]
ndarray4 = [1, 2, 3, 4]

n = 4

ID = []
value = []

for i in id:
    a = str(id.index(i)+1)
    for j in range(0,n):
        ID.append(i)
        value.append(eval('ndarray'+ a)[j])

df = pd.DataFrame({'ID':ID,'Value':value})

输出

ID  Value
0   userid1      1
1   userid1      2
2   userid1      3
3   userid1      4
4   userid2      1
5   userid2      2
6   userid2      3
7   userid2      4
8   userid3      1
9   userid3      2
10  userid3      3
11  userid3      4
12  userid4      1
13  userid4      2
14  userid4      3
15  userid4      4

答案 1 :(得分:0)

不同的方法

id = ['userid1', 'userid2', 'userid3']
ndarray1 = [1, 2, 3, 4]
ndarray2 = [1, 2, 3, 4]
ndarray3 = [1, 2, 3, 4]

concat = [ndarray1, ndarray2, ndarray3]

n = []
user = []

for i in range(len(concat)):
    for j in range(len(concat[i])):
        user.append(id[i])
        n.append(concat[i][j])

df = pd.DataFrame(data=[n, user]).T
df.columns = ['id', 'value']