根据来自多个文件的行对从数据帧中的单列进行排序

2024-04-25 08:55:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在对一个数据框进行排序,该数据框包含来自多个.csv文件的调查数据,并从每个.csv文件中输出一列,其中包含调查答案,如下所示:

                                               answer
0                                                 NaN
1                                           5-6 hours
2                                        Very restful
3                                  Somewhat refreshed
4                            [Home (dorm; apartment)]
5                                     [No one; alone]
6                   [Resting; napping; doing nothing]
7   [Not applicable; was not interacting with anyone]
8                                         Quite a bit
9                                        A little bit
10                                       A little bit
11                                       A little bit
12                                            Neutral
------------------------------------------------------
                                             answer
0                                               NaN
1                                         6-7 hours
2                                  Somewhat restful
3                                Slightly refreshed
4                  [Home (dorm; apartment);Vehicle]
5                                          [Family]
6           [Commuting; traveling;Eating; drinking]
7   [Talking on the phone;Interacting on Instagram]
8                                         Very much
9                                        Not at all
10                                      Quite a bit
11                                     A little bit
12                                          Neutral

我的目标是将数据转换成这种形式(基本上是按行对响应进行分组):

5-6 hours
6-7 hours

Very restful
Somewhat restful

Somewhat refreshed
Slightly refreshed

作为一个新手,我有点迷路,所以非常感谢您的帮助,谢谢


Tags: 文件csv数据answerrestfulhomebitnan
1条回答
网友
1楼 · 发布于 2024-04-25 08:55:18

基本上,您可以分别存储每个问题的答案

您可以通过迭代csv文件并将特定行存储到给定变量中来实现这一点

answer1List = []
answer2List = []

for i in range(len(csvList)):
    df = pd.read_csv(csvList[i])

    #Reading specific rows using iloc
    answer1List.append(df.iloc[1]['answer']   #Since the first answer is on the 2nd line
    answer2List.append(df.iloc[2]['answer']   #Since the 2nd answer is on the 3rd line

这样,您的输出变量将得到所需的答案

相关问题 更多 >