簡體   English   中英

python中導入csv文件時如何動態拆分列

[英]How to dynamically split the column while importing a csv file in python

我有一個 csv 文件,其中一列 integer 值和很多空行。 這些是不同學生在不同科目中獲得的分數,但並不是每個學生都參加了所有測試,因此,每個空白行之間的行數不同。 數據如下所示:

63
67
86
90

45
69
90

78
85
40
93
53
55
67

38
92
75
94
73

.
.
.

當我嘗試使用以下腳本導入此文件時,它會忽略空白行,output dataframe 如下所示:

df=pd.read_csv('input_data.txt',header=None)

63
67
86
90
45
69
90
78
85
40
93
53
55
67
.
.
.

每天學些新東西。 從來不知道 Pandas 默認跳過空行。

In [4]: pd.read_csv('input_data.txt', header=None, skip_blank_lines=False)
Out[4]:
       0
0   63.0
1   67.0
2   86.0
3   90.0
4    NaN
5   45.0
6   69.0
7   90.0
8    NaN
9   78.0
10  85.0
11  40.0
12  93.0
13  53.0
14  55.0
15  67.0
16   NaN
17  38.0
18  92.0
19  75.0
20  94.0
21  73.0

關於“將 NaN 拆分到不同的列”。 我不是 100% 確定你的意思。 N.netheless,這里有幾個有用的片段......

# load data
df = pd.read_csv('empty_rows.txt',
                 names=['score'], 
                 skip_blank_lines=False)

# Add an indicator column
df['has_score'] = ~df['score'].isna()

# Split the dataframe into two
gb_isna = df.groupby(~df['score'].isna())
df_has_score = gb_isna.get_group(True)
df_no_score = gb_isna.get_group(False)

# Or use indicator
gb_has_score = df.groupby('has_score')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM