Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

python - Pandas read data row by row

I have a csv file that looks like this

lon lat date1 date2 date3
120.55 23.2 1 2 3
1.66 2.3 4 5 6
question from:https://stackoverflow.com/questions/65661486/pandas-read-data-row-by-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have two options. Option one using stack:

df.set_index(['lon', 'lat'])
  .stack()
  .rename('date')
  .reset_index(level=2, drop=True)
  .reset_index()

       lon   lat  date
0   120.55  23.2     1
1   120.55  23.2     2
2   120.55  23.2     3
3   120.66  23.3     4
4   120.66  23.3     5
5   120.66  23.3     6
6   120.77  23.4     7
7   120.77  23.4     8
8   120.77  23.4     9
9   120.88  23.5    10
10  120.88  23.5    11
11  120.88  23.5    12

Option two using melt:

pd.melt(df, id_vars=['lon', 'lat'], value_vars=['date1', 'date2', 'date3'], value_name='date')
  .drop('variable', axis=1)

       lon   lat  date
0   120.55  23.2     1
1   120.66  23.3     4
2   120.77  23.4     7
3   120.88  23.5    10
4   120.55  23.2     2
5   120.66  23.3     5
6   120.77  23.4     8
7   120.88  23.5    11
8   120.55  23.2     3
9   120.66  23.3     6
10  120.77  23.4     9
11  120.88  23.5    12

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...